Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

c# - Getting all possible consecutive 4 digit numbers from a 10 digit number

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}
(dddd)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

enter image description here

C# demo:

var data = "2345678901";
var res = Regex.Matches(data, @"(?=(d{4}))")
            .Cast<Match>()
            .Select(p => p.Groups[1].Value)
            .ToList();
Console.WriteLine(string.Join("
", res));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...