gpt4 book ai didi

python - 找不到正确的正则表达式语法来匹配换行符或字符串结尾

转载 作者:太空狗 更新时间:2023-10-29 18:03:59 26 4
gpt4 key购买 nike

这似乎是一个非常简单的问题,但我无法在任何地方找到答案。

(注意:我使用的是 Python,但这应该无关紧要。)

假设我有以下字符串:

s = "foo\nbar\nfood\nfoo"

我只是想找到一个正则表达式来匹配“foo”的两个实例,而不是“food”,基于“food”中的“foo”没有紧跟换行符或字符串的结尾。

这可能是表达我的问题的一种过于复杂的方式,但它提供了一些具体的工作方法。

下面是我尝试过的一些东西,有结果(注:我要的结果是[foo\n, foo]):

foo[\n\Z] => ['foo\n']

foo(\n\Z) => ['\n', ''] <= 这似乎匹配换行符和 EOS,但不是 foo

foo($|\n) => ['\n', '']

(foo)($|\n) => [(foo,'\n'), (foo ,'')] <= 差不多了,这是一个可用的 B 计划,但我想找到完美的解决方案。

我发现唯一有用的是:

foo$|foo\n => ['foo\n', `'foo']

对于这样一个简单的例子来说这很好,但是很容易看出它如何在更大的表达式中变得笨拙(是的,这个 foo 东西是更大表达式的替代品我实际上正在使用)。


有趣的是:我能找到的最接近我的问题的问题是这个:In regex, match either the end of the string or a specific character

在这里,我可以简单地将 \n 替换为我的“特定字符”。现在,接受的答案使用正则表达式 /(&|\?)list=.*?(&|$)/。我注意到 OP 使用的是 JavaScript(问题用 javascript 标签标记),所以 JavaScript 正则表达式解释器可能不同,但是当我使用问题中给出的确切字符串和上面的正则表达式时Python,我得到了不好的结果:

>>> findall("(&|\?)list=.*?(&|$)", "index.php?test=1&list=UL")
[('&', '')]
>>> findall("(&|\?)list=.*?(&|$)", "index.php?list=UL&more=1")
[('?', '&')]

所以,我很难过。

最佳答案

>>> import re
>>> re.findall(r'foo(?:$|\n)', "foo\nbar\nfood\nfoo")
['foo\n', 'foo']

(?:...) 生成一个 non-capturing group .

之所以可行,是因为(来自 re module reference ):

re.findall(pattern, string, flags=0)

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

关于python - 找不到正确的正则表达式语法来匹配换行符或字符串结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14103942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com