简体   繁体   English

使用正则表达式对重复的字符?

[英]Repeated character in pair using regex?

I have a list of numbers, and using regex that look like this (\\d)(?=\\d*\\1) 我有一个数字列表,并使用看起来像这样的正则表达式(\\d)(?=\\d*\\1)

Example list of numbers: 示例数字列表:

1234 1234
5678 5678
5565 5565
5566 5566
5567 5567
5656 5656
1212 1212

Current Output using the expression: 当前输出使用表达式:

5565 5565
5566 5566
5567 5567
5656 5656
1212 1212

However, I want to extract list of numbers that are in 2 pairs in 4 numbers no matter what the arrangement is. 但是,我想提取4个数字的2对数字列表,无论安排是什么。 For example: 1122, 1212, 2211, 2121, 1221, 2112 例如: 1122,1212,2211,2121,1221,2112

Example of Desired Output: (where 5565, 5567 is false) 期望输出的示例:(其中5565,5567为假)

5566 5566
5656 5656
1212 1212

I am not familiar with regex, need some help. 我不熟悉正则表达式,需要一些帮助。

If your numbers are always 4 digits you can do something like this 如果您的号码总是4位数,您可以这样做

(?:(\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 . 使用\\1您可以引用第一个数字,使用\\2 ,第二个数字等。此正则表达式匹配三个可能的分布: abababbaaabb

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

Rather than Regex , if you want plain C# code, this will do 如果你想要普通的C#代码,而不是正则Regex

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 正如wb评论的那样,这可以缩短为

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

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

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