Python 正则表达式:仅精确匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45244813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:51:34  来源:igfitidea点击:

Python regular expression: exact match only

pythonregex

提问by smart

I have a very simple question, but I can't find an answer for this.

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

I have some string like:

我有一些字符串,如:

test-123

I want to have some smartregular expression for validation if this string exact match my condition.

smart如果此字符串与我的条件完全匹配,我想要一些正则表达式进行验证。

I expect to have a strings like:

我希望有一个像这样的字符串:

test-<number>

Where number should contains from 1 to * elements on numbers.

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

I'm trying to do something like this:

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

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.'

So, I can see both messages (with matching correct and wrong string), but I really expect to match only correct string.

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

Also, I was trying to use searchmethod instead of matchbut with no luck.

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

Ideas?

想法?

回答by hsz

Try with specifying the start and end rules in your regex:

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

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

回答by Sandeep PC

For exact match regex = r'^ (some-regex-here) $'

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

^ : Start of string

^ : 字符串的开始

$ : End of string

$ : 字符串结束

回答by Rajan saha Raju

I think It may help you -

我认为它可以帮助你 -

import re
pattern = r"test-[0-9]+$"
s = input()

if re.match(pattern,s) :
    print('matched')
else :
    print('not matched')

回答by Tom Wyllie

A pattern such as \btest-\d+\bshould do you;

一种\btest-\d+\b应该为您服务的模式;

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

Demo

演示

This requires the matching of word boundaries, so prevents other substrings from occuring after your desired match.

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

回答by Ajax1234

You can try re.findall():

你可以试试re.findall()

import re
correct_string = 'test-251'

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