[英]Regex for capturing 4 consecutive numbers in an ID
我需要一个公式来从某个索引开始,然后获取接下来的4个连续数字。 使用REGEX。 并测试它们是否在0000-4999的范围内。
^.{6}\d{4}$[0000-4999]
这是我尝试过的一些代码。 虽然我还很新,不了解正则表达式。
结果需要如下:
身份证号:
9202204720082
得到以下4个数字:4720
从索引7开始(假定索引从1开始)
因此,如果要获取索引7、8、9和10的数字,则需要确定数字。这样做是为了确定ID中的性别。
您的原始表达式很好,在这里我们可以对其稍作修改以:
^.{6}(\d{4}).+$
我们正在该组(\\d{4})
中捕获所需的数字。
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}`); }); }
jex.im可视化正则表达式:
您不需要为此使用正则表达式。 您只需获取子字符串即可达到相同的结果。 根据您的编程语言,您可能会执行以下操作:
var string = "9202204720082"; var index = 6; console.log(string.substring(index, index + 4));
string = '9202204720082'
index = 6
string[index, 4]
#=> "4720"
my $string = '9202204720082';
my $index = 6;
substr($string, $index, 4);
#=> "4720"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.