强制正则表达式在正则表达式的开头和结尾处完全匹配可选组

时间:2016-11-26 13:32:26

标签: regex go

如何强制正则表达式匹配正则表达式开头和结尾的可选组。例如:

package main import ( "fmt" "regexp" ) func main() { //here ok as exact match. The matched string starts by one of the keyword and ends by one of them. re := regexp.MustCompile(`(keyword1)\W*(?:\w+\W+){0,6}(keyword2)\W*(?:\w+\W+){0,6}(keyword3)`) text := "start text keyword1 optional word here then keyword2 again optional words then keyword3 others words after." s := re.FindAllString(text, -1) fmt.Println(s) //Here not exact match as the result doesn't start by keyword1 and end by keyword3 re = regexp.MustCompile(`(keyword1)*\W*(?:\w+\W+){0,6}(keyword2)\W*(?:\w+\W+){0,6}(keyword3)*`) text = "start text keyword1 optional word then keyword2 optional words keyword3 others words after." s = re.FindAllString(text, -1) fmt.Println(s) }

这里,keyword1和keywrod3分别位于正则表达式的开头和结尾,是可选的。我按此顺序查找keyword1,keyword2和keyword3。关键字之间最多可以有6个单词,但匹配的字符串应该以一个关键字开头,并以其中一个关键字结束。不需要额外的字符串。有没有办法做到这一点。任何建议都是受欢迎的。以下是代码和指向Go Playground的链接:

{{1}}

由于

0 个答案:

没有答案