正则表达式:检查字符串是否至少包含一位 [英] Regex: Check if string contains at least one digit

查看:53
本文介绍了正则表达式:检查字符串是否至少包含一位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的文本字符串:

I have got a text string like this:

test1test

我想使用正则表达式检查它是否至少包含一位数字.

I want to check if it contains at least one digit using a regex.

这个正则表达式会是什么样子?

What would this regex look like?

推荐答案

我很惊讶没有人提到最简单的版本:

I'm surprised nobody has mentioned the simplest version:

\d

这将匹配任何数字.如果您的正则表达式引擎支持 Unicode,这意味着它将匹配任何语言中定义为数字的任何内容,而不仅仅是阿拉伯数字 0-9.

This will match any digit. If your regular expression engine is Unicode-aware, this means it will match anything that's defined as a digit in any language, not just the Arabic numerals 0-9.

不需要像其他答案之一那样将它放在[方括号]中以将其定义为字符类;\d 本身就可以正常工作.

There's no need to put it in [square brackets] to define it as a character class, as one of the other answers did; \d works fine by itself.

由于它没有用 ^$ 锚定,它将匹配字符串的任何子集,因此如果字符串包含至少一个数字,则匹配.

Since it's not anchored with ^ or $, it will match any subset of the string, so if the string contains at least one digit, this will match.

而且没有必要增加 + 的复杂性,因为目标只是确定是否有至少一位数字.如果至少有一位数字,这将匹配;并且它会以最少的开销做到这一点.

And there's no need for the added complexity of +, since the goal is just to determine whether there's at least one digit. If there's at least one digit, this will match; and it will do so with a minimum of overhead.

这篇关于正则表达式:检查字符串是否至少包含一位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆