正则表达式的问题。nil切片和FindStringSubmatch。

huangapple go评论112阅读模式
英文:

Issues with regex. nil slice and FindStringSubmatch

问题

我正在尝试使用正则表达式匹配模式:

  1. random-text (800)

我正在做这样的事情:

  1. func main() {
  2. rando := "random-text (800)"
  3. parsedThing := regexp.MustCompile(`\((.*?)\)`)
  4. match := parsedThing.FindStringSubmatch(rando)
  5. if match[1] == "" {
  6. fmt.Println("do a thing")
  7. }
  8. if match[1] != "" {
  9. fmt.Println("do a thing")
  10. }
  11. }

我只想捕获括号内的内容,但FindString会解析括号。我也尝试过FindStringSubmatch,它很好,我可以在切片中指定捕获组,但是在我的单元测试中出现了错误,切片是空的。我需要测试空字符串,因为这可能是一个问题。有没有更好的正则表达式可以只捕获括号内的内容?或者有没有更好的处理空切片的错误处理方法?

英文:

I'm trying to regex a pattern:

  1. random-text (800)

I'm doing something like this:

  1. func main() {
  2. rando := "random-text (800)"
  3. parsedThing := regexp.MustCompile(`\((.*?)\)`)
  4. match := parsedThing.FindStringSubmatch(rando)
  5. if match[1] == "" {
  6. fmt.Println("do a thing")
  7. }
  8. if match[1] != "" {
  9. fmt.Println("do a thing")
  10. }
  11. }

I only want to capture what's in the parentheses but FindString is parsing the (). I've also tried FindStringSubmatch, which is great I can specify the capture group in the slice but then I have an error in my unit test, that the slice is . I need to test for an empty string as that's a thing that could happen. Is there a better regex, that I can use that will only capture inside the parentheses? Or is there a better way to error handle for an nil slice.

答案1

得分: 4

我通常会根据文档中的说明与nil进行比较:

> 返回值为nil表示没有匹配。

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. re := regexp.MustCompile(`\((.+)\)`)
  8. find := re.FindStringSubmatch("random-text (800)")
  9. if find != nil {
  10. fmt.Println(find[1] == "800")
  11. }
  12. }
英文:

I usually compare against nil, based on the documentation:

> A return value of nil indicates no match.

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. re := regexp.MustCompile(`\((.+)\)`)
  8. find := re.FindStringSubmatch("random-text (800)")
  9. if find != nil {
  10. fmt.Println(find[1] == "800")
  11. }
  12. }

huangapple
  • 本文由 发表于 2021年7月22日 06:03:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/68476975.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定