简体   繁体   English

正则表达式匹配特定长度的特定数字组?

[英]Regex to match a specific group of digits of certain length?

I found this: Regex to match digits of specific length but it talks about Python. 我发现了这一点:正则表达式可以匹配特定长度的数字,但是它涉及的是Python。 I am wanting to be able to get a group of random numbers of specific length. 我希望能够获得一组特定长度的随机数。 So if I have 167691#15316243 it will match 15316243 . 因此,如果我有167691#15316243 ,它将与15316243匹配。 I am not sure how to implement this. 我不确定如何执行此操作。 right now I have new RegExp('[0-9]+', "g"); 现在我有new RegExp('[0-9]+', "g"); which matches a group of numbers fine, but now I realized I will have some times when I have more than one group and I only want the group of eight numbers. 可以很好地匹配一组数字,但是现在我意识到,有时我会遇到多个组,而我只希望包含八个数字的组。

[0-9]+ - Matches one or more numbers
[0-9]{8} - Matches exactly 8 numbers.
[0-9]{8,10} - Matches between 8 and 10 numbers.
[0-9]{8,} - Matches 8 or more numbers.
[0-9]* - Matches zero or more numbers.
[0-9]? - Matches zero or one number.

You can specify the length of a matching set using {}. 您可以使用{}指定匹配集的长度。

For example: [0-9]{8} 例如: [0-9]{8}

Which will match any numbers from 0 to 9 with a specific length of 8 characters. 它将匹配从0到9的任何数字,特定长度为8个字符。

You can also specify a min/max range instead of forcing a specific legnth. 您也可以指定一个最小/最大范围,而不是强制特定的长度。 So if you wanted a min of 4 and a max of 8 the example would change to: [0-9]{4,8} 因此,如果您希望最小值为4,最大值为8,则示例将更改为: [0-9]{4,8}

Simply put the repetition amount in curly braces: 只需将重复量放在花括号中:

"167691#15316243".match(/\d{8}/g);

Here's the fiddle: http://jsfiddle.net/3r5vd/ 这是小提琴: http : //jsfiddle.net/3r5vd/


I'd suggest you read this article (scroll down to the section on Limiting Repetition). 建议您阅读本文 (向下滚动至“限制重复”部分)。

Here's a quote: 这是一个报价:

Modern regex flavors [...] have an additional repetition operator that allows you to specify how many times a token can be repeated. daccess-ods.un.org daccess-ods.un.org现代的regex风格具有附加的重复运算符,可让您指定令牌可以重复多少次。 The syntax is {min,max} , where min is a positive integer number indicating the minimum number of matches, and max is an integer equal to or greater than min indicating the maximum number of matches. 语法为{min,max} ,其中min是表示最小匹配数的正整数,而max是等于或大于min表示最大匹配数的整数。 If the comma is present but max is omitted, the maximum number of matches is infinite. 如果存在逗号但省略了max ,则最大匹配数是无限的。 So {0,} is the same as * , and {1,} is the same as + . 因此{0,}*相同,而{1,}+相同。
Omitting both the comma and max tells the engine to repeat the token exactly min times. 省略逗号和最大值都将指示引擎在min时间内重复令牌。

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

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