简体   繁体   English

去正则表达式查找子字符串

[英]Go regex find substring

I have a string:我有一个字符串:

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

I need to grep the version number to a string我需要将版本号 grep 到一个字符串

Tried,试过了,

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 :您需要指定捕获组以提取子匹配项,如包概述中所述

If 'Submatch' is present, the return value is a slice identifying the successive submatches of the expression.如果存在 'Submatch',则返回值是标识表达式的连续子匹配的切片。 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.子匹配 0 是整个表达式的匹配,子匹配 1 是第一个带括号的子表达式的匹配,依此类推。

Something along the lines of the following:类似于以下内容:

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
}

You'll of course want to check whether there actually is a submatch, or matches[1] will panic.您当然要检查是否确实存在子matches[1] ,否则matches[1]会恐慌。

如果您需要在其他地方使用/操作字符串变量中的值,您可以在 Marc 给出的给定示例中添加以下内容:

a := fmt.Sprintf("%s", matches[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM