【问题标题】:Python regular expression: exact match onlyPython 正则表达式:仅完全匹配
【发布时间】:2017-12-27 22:15:54
【问题描述】:

我有一个非常简单的问题,但我找不到答案。

我有一些类似的字符串:

test-123

如果这个字符串完全符合我的条件,我想要一些 smart 正则表达式进行验证。

我希望有这样的字符串:

test-<number>

其中 number 应包含从 1 到 * 的数字元素。

我正在尝试做这样的事情:

import re
correct_string = 'test-251'
wrong_string = 'test-123x'
regex = re.compile(r'test-\d+')
if regex.match(correct_string):
    print 'Matching correct string.'
if regex.match(wrong_string):
    print 'Matching wrong_string.'

所以,我可以看到两条消息(匹配正确和错误的字符串),但我真的希望只匹配正确的字符串。

另外,我尝试使用search 方法而不是match,但没有运气。

想法?

【问题讨论】:

标签: python regex


【解决方案1】:

精确匹配regex = r'^(some-regex-here)$'

^ : 字符串的开始

$ : 字符串结束

【讨论】:

    【解决方案2】:

    从 Python 3.4 开始,您可以使用 re.fullmatch 来避免将 ^$ 添加到您的模式中。

    >>> import re
    >>> p = re.compile(r'\d{3}')
    >>> bool(p.match('1234'))
    True
    
    >>> bool(p.fullmatch('1234'))
    False
    

    【讨论】:

      【解决方案3】:

      我想这可能对你有帮助 -

      import re
      pattern = r"test-[0-9]+$"
      s = input()
      
      if re.match(pattern,s) :
          print('matched')
      else :
          print('not matched')
      

      【讨论】:

        【解决方案4】:

        你可以试试re.findall():

        import re
        correct_string = 'test-251'
        
        if len(re.findall("test-\d+", correct_string)) > 0:
            print "Match found"
        

        【讨论】:

          【解决方案5】:

          \btest-\d+\b 这样的模式应该适合你;

          matches = re.search(r'\btest-\d+\', search_string)
          

          Demo

          这需要匹配单词边界,因此可以防止在您想要的匹配之后出现其他子字符串。

          【讨论】:

            【解决方案6】:

            尝试在您的正则表达式中指定开始和结束规则:

            re.compile(r'^test-\d+$')
            

            【讨论】:

            • 我明白了,谢谢。就在我的问题发布后,我发现了这个错误。
            • @smart 实际上只需要输入$,因为re.match 在正则表达式中自动假定^
            • @CDahn,我知道。泰!
            • 使用正则表达式的年头,我从来不知道“^”和“+$”是什么。更详细的解释在这里:stackoverflow.com/questions/34292024/…
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多