正则表达式如何处理正则表达式模式中间的“^”或“$”?
How regular expression handles `^` or `$` in the middle of regex pattern?
我正在尝试使用 python 中的正则表达式。我已经构建了如下所示的正则表达式。我知道 ^
用于匹配搜索字符串的开头。我已经通过包含多个 ^
的匹配模式构建了框架,但我不确定 re
将如何尝试匹配搜索字符串中的模式。
re.match("^def/^def", "def/def")
我原以为 re
会引发有关无效正则表达式的错误,但它不会引发任何错误并且 returns 没有匹配项。
所以,我的问题是 "^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 中的正则表达式。我已经构建了如下所示的正则表达式。我知道 ^
用于匹配搜索字符串的开头。我已经通过包含多个 ^
的匹配模式构建了框架,但我不确定 re
将如何尝试匹配搜索字符串中的模式。
re.match("^def/^def", "def/def")
我原以为 re
会引发有关无效正则表达式的错误,但它不会引发任何错误并且 returns 没有匹配项。
所以,我的问题是 "^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).
也可以创建带有可选组的模式,如果前面的所有模式都匹配空字符串,后面的 ^
仍然匹配。在无法匹配的地方使用 ^
不是解析器检查的内容,也不会引发错误。
您的特定模式永远不会匹配任何内容,因为中间的 ^
是无条件的,它前面的 /
不可能匹配必要的换行符,即使多行标志已启用。