繁体   English   中英

Python Regex 仅用于第一次匹配并忽略其他匹配

[英]Python Regex for only first match and ignore other matches

我试图在 python 中定义一个正则表达式来匹配以下字符串:

prefix:long-name

在示例文本中:

prefix:long-name
asdd prefix:long-name asddasd
asdd prefix:long-name;
 prefix:long-name
prefix:long-name:other-prefix:long-name:long-name
prefix:long-name

但它不应该在以下字符串匹配:

prefix:long-name:other-prefix:long-name:long-name

我尝试使用匹配组遵循正则表达式,但它无法正常工作:

([^;\{\}\s\*\+\'"]+)(:)([^;\{\}\s\*\+\'"]+)

问题是,正则表达式会匹配两个提到的字符串。

见 Regex101.com

字符串的末尾可能是行尾,但也可能是[\\s\\{\\}\\;]

有人有提示吗?

提前致谢。

您可以尝试使用以下模式:

(?<!\S)[^\s:]+:[^\s:]+(?!\S)

示例脚本:

inp = "asdd prefix:long-name asddasd prefix:long-name:other-prefix:long-name:long-name"
matches = re.findall(r'(?<!\S)[^\s:]+:[^\s:]+(?!\S)', inp)
print(matches)

这仅打印短匹配:

['prefix:long-name']

我可以解决的要求lookaheadlookbehind与以下正则表达式模式-assertion:

(?:^|(?<=[\\s\\{\\}\\;]))([^;{}\\s\\*\\+\\'\\"\\:\\/]+)(:)([^;{}\\s\\*\\+\\'\\"\\:\\/]+)(?:$|(?=[\\s\\{\\}\\;]))

有关示例请参阅 Regex101.com

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM