【发布时间】:2022-01-03 12:10:57
【问题描述】:
我正在尝试创建一个通过特定模式捕获字符串的 Go 正则表达式,除了以连续 2 个特殊字符结尾的字符串,并且不想使用前瞻,这可能吗?
这是我目前的模式(?:[a-zA-Z]+.)+\.[a-zA-Z]{2,}。
例如,给这个字符串:test.testing.com. test2.net.*
我想赶上test.testing.com 但不是 test2.net
【问题讨论】:
我正在尝试创建一个通过特定模式捕获字符串的 Go 正则表达式,除了以连续 2 个特殊字符结尾的字符串,并且不想使用前瞻,这可能吗?
这是我目前的模式(?:[a-zA-Z]+.)+\.[a-zA-Z]{2,}。
例如,给这个字符串:test.testing.com. test2.net.*
我想赶上test.testing.com 但不是 test2.net
【问题讨论】:
你可以用
捕捉那部分\b([a-zA-Z]+(?:\.[a-zA-Z]+)*)\b(?:.?$|[[:punct:]][^[:punct:]]|[^[:punct:]][[:punct:]])
请参阅regex demo。 详情:
\b - 单词边界([a-zA-Z]+(?:\.[a-zA-Z]+)*)\b - 单词边界(?: - 非捕获组的开始:
.?$ - 任何可选的单个字符(换行符除外)和字符串结尾| - 或[[:punct:]][^[:punct:]] - 一个标点符号和一个非标点符号| - 或[^[:punct:]][[:punct:]] - 非标点符号和标点符号字符) - 非捕获组结束。见Go demo:
package main
import (
"fmt"
"regexp"
)
func main() {
markdownRegex := regexp.MustCompile(`\b([a-zA-Z]+(?:\.[a-zA-Z]+)*)\b(?:.?$|[[:punct:]][^[:punct:]]|[^[:punct:]][[:punct:]])`)
str := `test.testing.com. test2.net.*`
for _, result := range markdownRegex.FindAllStringSubmatch(str, -1) {
fmt.Printf("%s\n", result[1])
}
}
// => test.testing.com
【讨论】: