简体   繁体   中英

Repeated character in pair using regex?

I have a list of numbers, and using regex that look like this (\\d)(?=\\d*\\1)

Example list of numbers:

1234
5678
5565
5566
5567
5656
1212

Current Output using the expression:

5565
5566
5567
5656
1212

However, I want to extract list of numbers that are in 2 pairs in 4 numbers no matter what the arrangement is. For example: 1122, 1212, 2211, 2121, 1221, 2112

Example of Desired Output: (where 5565, 5567 is false)

5566
5656
1212

I am not familiar with regex, need some help.

If your numbers are always 4 digits you can do something like this

(?:(\d)(\d)\1\2)|(?:(\d)\3(\d)\4)|(?:(\d)(\d)\6\5)

So, if you have four digit numbers you can only have two different digits in each number. With \\1 you can reference the first digit, with \\2 the second, etc. This regex matches the three possible distributions: abab , abba and aabb .

Example: https://regex101.com/r/cP4nI5/2

Rather than Regex , if you want plain C# code, this will do

int number = 1212;
var isDoublePair = number.ToString()
                    .ToCharArray()
                    .GroupBy(c => c)
                    .Select(grp => grp.Count())
                    .All(count => count == 2);

As commented by wb, this can be shortened to

var isDoublePair = number.ToString()
                     .GroupBy(c => c)
                     .All(g => g.Count() == 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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