正则表达式查找子字符串 [英] Go regex find substring

查看:120
本文介绍了正则表达式查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

s := "root 1 12345 /root/pathtomyfolder/jdk/jdk.1.8.0.25 org.catalina.startup"

我需要将版本号grep到字符串中

I need to grep the version number to a string

尝试过

var re = regexp.MustCompile(`jdk.*`)
func main() {
matches := re.FindStringSubmatch(s)
fmt.Printf ("%q", matches)
}

推荐答案

您需要指定捕获组以提取子匹配项,如

You need to specify capturing groups to extract submatches, as described in the package overview:

如果存在子匹配",则返回值是一个片,用于标识表达式的连续子匹配.子比赛是的比赛括号内的子表达式(也称为捕获组)正则表达式,按从左到右的顺序编号开括号.子匹配0是整个表达式的匹配,submatch 1第一个带括号的子表达式的匹配,依此类推上.

If 'Submatch' is present, the return value is a slice identifying the successive submatches of the expression. Submatches are matches of parenthesized subexpressions (also known as capturing groups) within the regular expression, numbered from left to right in order of opening parenthesis. Submatch 0 is the match of the entire expression, submatch 1 the match of the first parenthesized subexpression, and so on.

以下内容:

func main() {
    var re = regexp.MustCompile(`jdk\.([^ ]+)`)
    s := "root 1 12345 /root/pathtomyfolder/jdk/jdk.1.8.0.25 org.catalina.startup"
    matches := re.FindStringSubmatch(s)
    fmt.Printf("%s", matches[1])
    // Prints: 1.8.0.25
}

您当然要检查是否确实存在子匹配项,否则 matches [1] 会惊慌.

You'll of course want to check whether there actually is a submatch, or matches[1] will panic.

这篇关于正则表达式查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆