【问题标题】:Regex match string where symbol is not repeated不重复符号的正则表达式匹配字符串
【发布时间】:2021-04-05 05:43:04
【问题描述】:

我有这样的字符串:

group items % together into% 错误

characters % that can match any single 是的

如何匹配不重复符号% 的句子?

我尝试过这种模式,但发现第一个匹配句子带有符号%

[%]{1}

【问题讨论】:

标签: regex string repeat


【解决方案1】:

您可以在 python 中使用此正则表达式来返回包含多个 % 的行的失败:

^(?!([^%]*%){2}).+

RegEx Demo

(?!([^%]*%){2}) 是一个负前瞻,如果在行开始后两次找到%,则匹配失败。

【讨论】:

    【解决方案2】:

    您可以按如下方式使用re.search

    items = ['group items % together into%', 'characters % that can match any single']
    for item in items:
        output = item
        if re.search(r'^.*%.*%.*$', item):
            output = output + ' FALSE'
        else:
            output = output + ' TRUE'
        print(output)
    

    打印出来:

    group items % together into% FALSE
    characters % that can match any single TRUE
    

    【讨论】:

      【解决方案3】:

      数一数(Python):

      >>> s = 'blah % blah %'
      >>> s.count('%') == 1
      False
      >>> s = 'blah % blah'
      >>> s.count('%') == 1
      True
      

      使用正则表达式:

      >>> re.match('[^%]*%[^%]*$','gfdg%fdgfgfd%')
      >>> re.match('[^%]*%[^%]*$','blah % blah % blah')
      >>> re.match('[^%]*%[^%]*$','blah % blah blah')
      <re.Match object; span=(0, 16), match='blah % blah blah'>
      

      re.match必须从字符串的开头匹配,如果使用re.search,则使用^(匹配字符串的开头),它可以匹配字符串的中间。

      >>> re.search('^[^%]*%[^%]*$','gfdg%fdgfgfd%')
      >>> re.search('^[^%]*%[^%]*$','gfdg%fdgfgfd')
      <re.Match object; span=(0, 12), match='gfdg%fdgfgfd'>
      

      【讨论】:

      • 您的正则表达式将此字符串与双 % 符号匹配,并且此结果不正确。字符串gfdg%fdgfgfd%。这是演示regex101.com/r/QYM9Xb/1
      • @AndreasHunter 查看编辑。在 Python 中,re.match 必须从字符串的开头匹配,所以它是正确的。你没有提到语言。如果您使用的任何语言都不能这样工作,请使用 ^[^%]%[^%]$
      【解决方案4】:

      我假设您问题中的“句子”与输入文本中的一行相同。有了这个假设,您可以使用以下内容:

      ^[^%\r\n]*(%[^%\r\n]*)?$

      这与多行和全局标志一起,将匹配输入字符串中包含 0 或 1 个“%”符号的所有行。

      ^ 匹配行首
      [^%\r\n]* 匹配 0 个或多个不是 '%' 或新行的字符
      (...)? 匹配括号中内容的 0 个或 1 个实例% 匹配 '%' 字面意思
      $ 匹配行尾

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多