匹配数字和字符串的正则表达式(Regular expression for matching numbers and strings)

编程入门 行业动态 更新时间:2024-10-04 17:19:56
匹配数字和字符串的正则表达式(Regular expression for matching numbers and strings)

我有一系列的话,如下所示

476pe e586 9999 rrr ABCF

我必须编写一个正则表达式,将数字和数字与字母匹配。从上面的字符串我必须匹配

476pe e586 9999

我试着编写一个正则表达式,如下所示

^[\D]*[0-9]+[\D]*$

但它不起作用。 我尝试使用在线正则表达式工具http://rubular.com/r/HQE2vG0pbu ,它显示整个字符串匹配。

i have series of words as given below

476pe e586 9999 rrr ABCF

i have to write a regular expression that will match the numbers and numbers with alphabets.From the above strings i have to match only

476pe e586 9999

I tried to write a regular expression as given below

^[\D]*[0-9]+[\D]*$

but it doesn't work. I tried this with an online regex tool, http://rubular.com/r/HQE2vG0pbu and it shows that the entire string is matching.

最满意答案

正则表达式的问题在于\D可以是除数字之外的任何内容 ,因此它将错误地匹配该位置中具有特殊字符的字符串,并且无法匹配具有多个数字组的字符串。

相反,尝试^[0-9a-zA-Z]*[0-9][0-9a-zA-Z]*$ 。 这将匹配任意数量的数字或字母,后跟数字,以及任意数量的数字或字母。

这是一个演示 ......

The problem with your regex is that \D can be anything except a number, so it will wrongly match strings with special characters in that position, and fail to match strings with more than one group of numbers.

Instead, try something like ^[0-9a-zA-Z]*[0-9][0-9a-zA-Z]*$. This will match any numbers of numbers or letters, followed by a number, and again any number of numbers or letters.

And here's a demo...

更多推荐

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

发布评论

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

>www.elefans.com

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