python正则表达式古怪

2024-06-24 12:13:44 发布

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

我认为我可以使用正则表达式-但这让我感到困惑-我有一行python代码:

dependencies = re.findall( r"-- *depends *on *([^ ]*.*[^ ]) *$", script, re.MULTILINE)    

这在以下情况下非常有效:

"-- depends on    b    "    -> ["b"]
"-- depends on b"           -> ["b"]
"--dependson  green things    \n-- depends on red things\nother stuff"" -> ["green things", "red things"]
"-- depends on b \n-- depends on c" -> ["b", "c"]

但对我来说不起作用

"-- depends on b\n-- depends on c" -> ["b\n-- depends on c"]

我明白了,在换行之前$matches这个事实会有些奇怪,但我不明白的是如何修复正则表达式


Tags: 代码reonscript情况dependenciesgreenred
2条回答

它将“\n”换行符匹配为“非空格”,您可以这样修复它,例如:

*depends *on *([^ \n]*.*[^ \n]) *$

你可能真的想要这样的东西:

\s*depends\s*on\s*(\S*.*\S)\s*$

\s表示“任何空间类型”,而\S表示任何非空间类型

在Python中re^{} option只重新定义了两个锚点^$的行为,它们开始匹配任何的开始和结束,而不仅仅是整个字符串

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. Corresponds to the inline flag (?m).

接下来,被[^ ]求反的字符类匹配除文本规则空格字符以外的任何字符\x20,十二月代码32)。因此,[^ ]*匹配除空格以外的任何零个或多个字符(也包括换行符)

你可以用

  *depends *on *(.*\S) *$

或者,如果可以使用不间断空格或其他水平Unicode空格

 [^\S\r\n]*depends[^\S\r\n]*on[^\S\r\n]*(.*\S)[^\S\r\n]*$

在Python中,可以使用

h = r'[^\S\r\n]'
pattern = fr' {h}*depends{h}*on{h}*(.*\S){h}*$'

{h}*(.*\S)部分完成这项工作:首先匹配并使用零个或多个空格,然后将除换行符以外的任何零个或多个字符(尽可能多(.*)+非空白字符(\S)捕获到组1中

相关问题 更多 >