简体   繁体   English

正则表达式验证数字字符串

[英]Regex validating string of numbers

I am trying create regex witch will start with some number like 230, 420, 7456. Then could be some number in interval 1-9 but the final length must be 9.我正在尝试创建正则表达式,女巫将以 230、420、7456 之类的数字开头。然后可能是区间 1-9 中的某个数字,但最终长度必须为 9。

For example 230888333 or 745623777例如230888333745623777

I create this:我创建了这个:

([(230|420|7456)[0-9]{1,}]{9})

But it is not correct.但这是不正确的。 Any idea how to make this correct?知道如何纠正吗?

Thaks.谢谢。

The pattern that you tried is not anchored, and the current notation uses a character class [...] instead of a grouping (the ]{9} part at the end repeats 9 times a ] char)您尝试的模式未锚定,当前符号使用字符类[...]而不是分组(末尾的]{9}部分重复 9 次]字符)


If you use C# then use [0-9] to match a digit 0-9.如果您使用 C#,则使用[0-9]匹配数字 0-9。

You can either assert 9 digits in total:您可以断言总共 9 位数字:

^(?=[0-9]{9}$)(?:230|420|7456)[0-9]+$

Regex demo正则表达式演示

Or write an alternation for different leading lengths of digits:或者为不同的前导数字长度写一个交替:

^(?:(?:230|420)[0-9]{6}|7456[0-9]{5})$

Regex demo正则表达式演示

You can simply add a check for length first and then simple regex您可以先简单地添加长度检查,然后再添加简单的正则表达式

 function checkString(str){ return str.length === 9 && /^(?:230|420|7456)\d+$/.test(str) } console.log(checkString("230888333")) console.log(checkString("745623777")) console.log(checkString("123")) console.log(checkString("230888333123"))

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

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