简体   繁体   English

正则表达式,用于捕获ID中的4个连续数字

[英]Regex for capturing 4 consecutive numbers in an ID

I need a formula to start at aa certain index and then get the next 4 consecutive numbers. 我需要一个公式来从某个索引开始,然后获取接下来的4个连续数字。 Using REGEX. 使用REGEX。 And testing whether they are in the range of 0000-4999. 并测试它们是否在0000-4999的范围内。

^.{6}\d{4}$[0000-4999]

This is some code I have tried. 这是我尝试过的一些代码。 Although I'm still new and don't understand regex. 虽然我还很新,不了解正则表达式。

The outcome needs to be as follows: 结果需要如下:

ID Number: 身份证号:

9202204720082

Get the following 4 numbers: 4720 得到以下4个数字:4720

Starting at index 7 (presuming indexes starts at 1) 从索引7开始(假定索引从1开始)

So want to get numbers if indexes 7,8,9, and 10. This is done to determine the gender in an ID. 因此,如果要获取索引7、8、9和10的数字,则需要确定数字。这样做是为了确定ID中的性别。

May be this can help : 也许这可以帮助:

(?<=\d{6})\d{4}(?<=\d{3})

you can check it out in the regex101 link : Link to Regex 您可以在regex101链接中查看它: 链接到Regex

Your original expression is just fine, here we can slightly modify it to: 您的原始表达式很好,在这里我们可以对其稍作修改以:

^.{6}(\d{4}).+$

which we are capturing our desired digits in this group (\\d{4}) . 我们正在该组(\\d{4})中捕获所需的数字。

DEMO DEMO

 const regex = /^.{6}(\\d{4}).+$/gm; const str = `9202204720082`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } 

RegEx Circuit RegEx电路

jex.im visualizes regular expressions: jex.im可视化正则表达式:

在此处输入图片说明

You don't need to use a regex for this. 您不需要为此使用正则表达式。 You could achieve the same result by simply getting a substring. 您只需获取子字符串即可达到相同的结果。 Depending on your programming language you might do something like this: 根据您的编程语言,您可能会执行以下操作:

JavaScript JavaScript的

 var string = "9202204720082"; var index = 6; console.log(string.substring(index, index + 4)); 

Ruby 红宝石

string = '9202204720082'
index = 6

string[index, 4]
#=> "4720"

Perl Perl的

my $string = '9202204720082';
my $index = 6;

substr($string, $index, 4);
#=> "4720"

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

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