英文:
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")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论