我正在尝试在 python 中使用正则表达式。我已经构建了如下所示的正则表达式。我知道 ^
用于匹配搜索字符串的开头。我通过包含多个 ^
的匹配模式构建了框架,但我不确定 re
将如何尝试匹配搜索字符串中的模式。
re.match("^def/^def", "def/def")
我原以为 re
会引发错误,关于无效的正则表达式,但它不会引发任何错误,也不会返回任何匹配项。
所以,我的问题是 "^def/^def"
或 "$def/$def"
一个有效的正则表达式?
最佳答案
您没有无效的正则表达式,^
在字符串中间有合法用途。当您使用 re.M
flag例如:
When specified, the pattern character
'^'
matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character'$'
matches at the end of the string and at the end of each line (immediately preceding each newline).
也可以创建带有可选组的模式,如果前面的所有模式都匹配空字符串,后面的 ^
仍然匹配。在无法匹配的地方使用 ^
不是解析器检查的内容,也不会引发错误。
你的特定模式永远不会匹配任何东西,因为中间的 ^
是无条件的,它前面的 /
不可能匹配必要的换行符,即使启用了多行标志。
关于python - 正则表达式如何处理正则表达式模式中间的 `^` 或 `$`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49231405/