我认为我可以使用正则表达式-但这让我感到困惑-我有一行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这个事实会有些奇怪,但我不明白的是如何修复正则表达式
它将“\n”换行符匹配为“非空格”,您可以这样修复它,例如:
*depends *on *([^ \n]*.*[^ \n]) *$
你可能真的想要这样的东西:
\s*depends\s*on\s*(\S*.*\S)\s*$
\s
表示“任何空间类型”,而\S
表示任何非空间类型在Python中} option 只重新定义了两个锚点
re
,^{^
和$
的行为,它们开始匹配任何行的开始和结束,而不仅仅是整个字符串:接下来,被
[^ ]
求反的字符类匹配除文本规则空格字符以外的任何字符(\x20
,十二月代码32)。因此,[^ ]*
匹配除空格以外的任何零个或多个字符(也包括换行符)你可以用
或者,如果可以使用不间断空格或其他水平Unicode空格
在Python中,可以使用
{h}*(.*\S)
部分完成这项工作:首先匹配并使用零个或多个空格,然后将除换行符以外的任何零个或多个字符(尽可能多(.*
)+非空白字符(\S
)捕获到组1中相关问题 更多 >
编程相关推荐