【问题标题】:Python Regex for only first match and ignore other matchesPython Regex 仅用于第一个匹配项并忽略其他匹配项
【发布时间】:2020-06-16 09:55:17
【问题描述】:

我正在尝试在 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\*\+\'"]+)

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

See Regex101.com

字符串的末尾可以是行尾,但也可以是[\s\{\}\;] 之一。

有人有小费吗?

提前致谢。

【问题讨论】:

  • 那么字符串的末尾是什么,如果不是文件结尾或行结尾?
  • 我更新了我的帖子。它可能是 [\s\{\{\;] .
  • 为什么你的角色类别中有两次{?还是您的意思是文字字符串[\s{{;]?还是只是\s{{;?不清楚……
  • 谢谢。我用更多信息更新了我的帖子。

标签: python regex


【解决方案1】:

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

(?<!\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']

【讨论】:

  • 不匹配。例如。 abc:def:ghi:jkl 会匹配 ghi:jkl,但它不应该。
  • 你有一个错误。很可能它是基于复制和粘贴的。您忘记了上述模式中的^$,但在示例脚本中使用了它!此外,使用 regex101.com 而不是 rextester.com 可能会更好!
  • @csabinho 是的,你是对的。我只使用 Rextester 向您展示工作 Python 代码,否则我同意您的看法。
  • @TimBiegeleisen 现在,它可以工作了。见regex101.com/r/UD7ZnF/8。我会把你的答案标记为正确。
【解决方案2】:

我可以使用lookaheadlookbehind-assertion 以及以下正则表达式模式来解决要求:

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

See Regex101.com 为例。

【讨论】:

  • 查看我的答案以获得更好的方法。您可以只使用一个否定的前瞻来排除长匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
相关资源
最近更新 更多