问题描述
我正在尝试制作一个正则表达式,以从10位数字中获取所有可能的连续4位数字。像
num = 2345678901;
输出:
2345
, 3456
, 4567
, 5678
, 6789
, 7890
, 8901
这些简单的正则表达式无法正常工作:
[\d] {4}
(\d\d\d\d)
您需要使用(?=(\d {4}))
正则表达式来匹配重叠的匹配项。
请参见
:
var data = 2345678901;
var res = Regex.Matches(data,@(?=(\d {4}))))
.Cast< Match>()
.Select(p => ; p.Groups [1] .Value)
.ToList();
Console.WriteLine(string.Join( \n,res));
I am trying to make a regex to get all the possible consecutive 4 digit numbers from a 10 digit number. Like
num = "2345678901";
Output :2345
, 3456
, 4567
, 5678
, 6789
, 7890
, 8901
These simple regex are not working:
[\d]{4}
(\d\d\d\d)
You need to use (?=(\d{4}))
regex to match overlapping matches.
See the regex demo
The regexes you are using are all consuming the 4 digit chunks of text, and thus the overlapping values are not matched. With (?=...)
positive lookahead, you can test each position inside the input string, and capture 4 digit chunks from those positions, without consuming the characters (i.e. without moving the regex engine pointer to the location after these 4 digit chunks).
var data = "2345678901";
var res = Regex.Matches(data, @"(?=(\d{4}))")
.Cast<Match>()
.Select(p => p.Groups[1].Value)
.ToList();
Console.WriteLine(string.Join("\n", res));
这篇关于从10位数字中获取所有可能的连续4位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!