使用正则表达式检查整个字符串

编程入门 行业动态 更新时间:2024-10-24 00:25:57
本文介绍了使用正则表达式检查整个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试检查字符串是否为数字,因此正则表达式 "\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 = repile("\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()

更多推荐

使用正则表达式检查整个字符串

本文发布于:2023-10-23 13:48:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521000.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!