简体   繁体   English

使用 Regex golang 查找所有字符串匹配

[英]Find all string matches with Regex golang

I am trying to return an array, or slice, with all the matches for a specific regex expression against a string.我正在尝试返回一个数组或切片,其中包含针对字符串的特定正则表达式的所有匹配项。 The string is:字符串是:

{city}, {state} {zip}

I want to return an array with all the matches of strings between curly braces.我想返回一个数组,其中包含花括号之间的所有字符串匹配项。 I have tried using the regexp package to accomplish this but cannot figure out how to return what I am looking for.我曾尝试使用regexp包来完成此操作,但无法弄清楚如何返回我正在寻找的内容。 This is my current code:这是我当前的代码:

r := regexp.MustCompile("/({[^}]*})/")
matches := r.FindAllString("{city}, {state} {zip}", -1)

But, all it returns is an empty slice every time no matter what I try.但是,无论我尝试什么,它每次返回的都是一个空切片。

First, you do not need the regex delimiters.首先,您不需要正则表达式分隔符。 Second, it is a good idea to use raw string literals to define a regex pattern where you need to use only 1 backslash to escape regex metacharacters.其次,使用原始字符串文字来定义正则表达式模式是一个好主意,您只需要使用 1 个反斜杠来转义正则表达式元字符。 Third, the capturing group is only necessary if you need to get the values without { and } , thus, you may remove it to get {city} , {state} and {zip} .第三,仅当您需要获取没有{}的值时才需要捕获组,因此,您可以将其删除以获取{city}{state}{zip}

You may use FindAllString to get all matches:您可以使用FindAllString来获取所有匹配项:

r := regexp.MustCompile(`{[^{}]*}`)
matches := r.FindAllString("{city}, {state} {zip}", -1)

See the Go demo .请参阅Go 演示

To only get the parts between curly braces use FindAllStringSubmatch with a pattern that contains capturing parentheses, {([^{}]*)} :要仅获取大括号之间的部分,请使用FindAllStringSubmatch和包含捕获括号的模式{([^{}]*)}

r := regexp.MustCompile(`{([^{}]*)}`)
matches := r.FindAllStringSubmatch("{city}, {state} {zip}", -1)
for _, v := range matches {
    fmt.Println(v[1])
}

See this Go demo .请参阅此 Go 演示

Regex details正则表达式详情

  • { - a literal { char { - 文字{字符
  • ([^{}]*) - a capturing group that matches any 0 or more (due to the * quantifier) characters other than { and } ( [^...] is a negated character class matching any char but the one(s) specified between [^ and ] ) ([^{}]*) - 匹配除{}之外的任何 0 个或多个(由于*量词)字符的捕获组( [^...]是匹配任何字符的否定字符类,但一个( s) 在[^]之间指定)
  • } - a literal } char } - 文字}字符

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

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