Regex中的锚定

2024-04-25 04:00:32 发布

您现在位置:Python中文网/ 问答频道 /正文

  1. 在Python正则表达式中,必须^or$ 只出现一次?在
  2. 我试着把两条线

    ^(.*\|.*)$^.*$
    

    它不起作用。你怎么配 几行?

注意:我不是用Python编程,而是在我的编辑器gedit中使用Python风格的Regex。在

谢谢和问候!在


Tags: or风格编程编辑器regex问候两条线gedit
3条回答

看看^{}。在

我引用:

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).

By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string.

你必须使用re.多行(或者甚至雷多尔如果您更改regex,并且取决于您实际想要匹配/执行的操作)

re.MULTILINE

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).

By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string.

http://docs.python.org/library/re.html

顺便说一句,你在用-^(.*\|.*)$^.*$-这不是一个很好的正则表达式!(忽略了一个事实,你有多个$和{},这是问题的重点。)在

正如其他答案所说,您正在寻找re.MULTILINE,但即使这样,您的regex也无法工作。在

$匹配换行符之前的位置,^匹配行的开头,因此regex中间的$^永远不会匹配。例如:

>>> re.search("^(.*)$^.*$", multiline_string, re.M)    # won't match
>>> re.search("^(.*)$\n^.*$", multiline_string, re.M)  # will match
<_sre.SRE_Match object at 0xb7f3e5e0>

您需要一些东西来匹配$^之间的行尾字符。在

相关问题 更多 >