简体   繁体   English

正则表达式要求至少一个数字或留空

[英]Regex to require at least one digit or to be left blank

Need some advice for a regex expression I am trying to create. 需要一些我正在尝试创建的正则表达式的建议。

I need to check whether the string contains at least one digit (0-9) OR it can be left empty. 我需要检查字符串是否包含至少一个数字(0-9)或者它可以留空。

This is my regex that checks for a digit: 这是检查数字的正则表达式:

(.*[0-9]){1}.*$

How can I modify this to allow for empty string? 如何修改它以允许空字符串?

You can use an optional non-capturing group like this 您可以使用这样的可选 非捕获组

^(?:.*?\d.*)?$

See demo at regex101 请参阅regex101上的演示

Perhaps you could try something like this: 也许你可以尝试这样的事情:

^($|.*[0-9])

Even though ^ and $ do not consume any characters, they can still be used inside, as well as outside, of groups. 即使^$不消耗任何字符,它们仍然可以在组内部和外部使用。

Also, depending on what you're doing, you may not even need the groups: 此外,根据您正在做的事情,您可能甚至不需要这些组:

^$|.*[0-9]

You could use 你可以用

^(?:(?=\D*\d)|^$).*


This says: 这说:

 ^ # start of the string (?: (?=\\D*\\d) # either match at least one number | # or ^$) # the empty string .* # 0+ characters 

See a demo on regex101.com . 请参阅regex101.com上的演示

Apply both conditions with a ? 适用两种条件? (optional) mark: (可选)标记:

^(\D*\d.*)?$

OP mentioned jquery in comments below the question. OP在问题下面的评论中提到了jquery。

You can simply test to see if a digit exists in the string using \\d and test() and also test the string's length as shown in the snippet below. 您可以使用\\dtest()字符串中是否存在数字,并test()字符串的长度,如下面的代码段所示。 This greatly simplifies the regex pattern and the test. 这极大地简化了正则表达式模式和测试。

 var a = [ 'cdjk2d', '', //valid 'abc', ' ' //invalid ] a.forEach(function(s){ if(s.length === 0 || /\\d/.test(s)) { console.log(s) } }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM