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

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

Issues with regex. nil slice and FindStringSubmatch

问题

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

random-text (800)

我正在做这样的事情:

func main() {

	rando := "random-text (800)"
	parsedThing := regexp.MustCompile(`\((.*?)\)`)
	match := parsedThing.FindStringSubmatch(rando)
	if match[1] == "" {
		fmt.Println("do a thing")
	}
	if match[1] != "" {
		fmt.Println("do a thing")
	}

}

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

英文:

I'm trying to regex a pattern:

random-text (800)

I'm doing something like this:

func main() {

	rando := "random-text (800)"
	parsedThing := regexp.MustCompile(`\((.*?)\)`)
	match := parsedThing.FindStringSubmatch(rando)
	if match[1] == "" {
		fmt.Println("do a thing")
	}
		if match[1] != "" {
		fmt.Println("do a thing")
	}
	
}

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表示没有匹配。

package main

import (
   "fmt"
   "regexp"
)

func main() {
   re := regexp.MustCompile(`\((.+)\)`)
   find := re.FindStringSubmatch("random-text (800)")
   if find != nil {
      fmt.Println(find[1] == "800")
   }
}
英文:

I usually compare against nil, based on the documentation:

> A return value of nil indicates no match.

package main

import (
   "fmt"
   "regexp"
)

func main() {
   re := regexp.MustCompile(`\((.+)\)`)
   find := re.FindStringSubmatch("random-text (800)")
   if find != nil {
      fmt.Println(find[1] == "800")
   }
}

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:

确定