使用正则表达式检查整个字符串 [英] Checking whole string with a regex
本文介绍了使用正则表达式检查整个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试检查字符串是否为数字,因此正则表达式 "\d+" 看起来不错.但是,由于某种原因,该正则表达式也适合78.46.92.168:8000",这是我不想要的,有一点代码:
I'm trying to check if a string is a number, so the regex "\d+" seemed good. However that regex also fits "78.46.92.168:8000" for some reason, which I do not want, a little bit of code:
class Foo():
_rex = re.compile("\d+")
def bar(self, string):
m = _rex.match(string)
if m != None:
doStuff()
当输入ip地址时调用doStuff().我有点困惑,."怎么办?还是:"匹配\d"?
And doStuff() is called when the ip adress is entered. I'm kind of confused, how does "." or ":" match "\d"?
推荐答案
\d+
匹配字符串内的任意正数位数,因此它匹配第一个 78
并成功.
\d+
matches any positive number of digits within your string, so it matches the first 78
and succeeds.
使用^\d+$
.
或者,更好:"78.46.92.168:8000".isdigit()
这篇关于使用正则表达式检查整个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文