查找与正则表达式golang匹配的所有字符串 [英] Find all string matches with Regex golang

查看:1673
本文介绍了查找与正则表达式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}

我想返回一个包含花括号之间所有字符串匹配项的数组.我尝试使用 regexp 包来完成此操作,但无法弄清楚如何返回我要查找的内容.这是我当前的代码:

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. 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.

推荐答案

首先,您不需要正则表达式定界符.其次,使用原始字符串文字定义一个正则表达式模式是个好主意,您只需要使用1个反斜杠即可转义正则表达式元字符.第三,仅当需要获取不带{}的值时,捕获组才是必需的,因此,可以将其删除以获取{city}{state}{zip}.

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. 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}.

您可以使用 FindAllString 来获取所有匹配项:

You may use FindAllString to get all matches:

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

请参见开始演示.

要仅获取花括号之间的部分,请使用 FindAllStringSubmatch 包含捕获括号的模式,{([^{}]*)}:

To only get the parts between curly braces use FindAllStringSubmatch with a pattern that contains capturing parentheses, {([^{}]*)}:

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

请参见此Go演示.

正则表达式详细信息

  • {-文字{ char
  • ([^{}]*)-一个与{}以外的任何0个或多个(由于*量词决定)字符匹配的捕获组([^...]是一个与所有除char之外的任何char匹配的否定字符类(c)在[^]之间指定)
  • }-文字} char
  • { - 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 ])
  • } - a literal } char

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

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