python - 正则表达式如何处理正则表达式模式中间的 `^` 或 `$`?

标签 python regex re-python

我正在尝试在 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/

相关文章:

java - 表情符号的正则表达式

python - 为什么从命令行运行时导入失败,而从 PyCharm 运行时导入成功?

Python Django httpd - [通知] child pid XXXXX exit signal Segmentation fault (11)

python - 控制台中西里尔符号的问题

使用 JwT token 身份验证对 HTTP Rest API 的 Python 发布请求生成重复的帖子

c# - 如何按 X% 匹配 2 个字符串(即 >90% 匹配)

php - 正则表达式中的波浪号运算符