正则表达式匹配前两次出现大写字母后跟几个小写字母

时间:2014-04-04 17:03:29

标签: c# regex

我一直在查看这里的示例,了解如何进行类似的正则表达式匹配,但我无法让它适用于我的情况。

我有一个像ThisisMystringItsTooLong这样的字符串,我希望收回ThiMys大写字母的前两次出现,然后是后面的两个小写字母) 但是,如果字符串只有Thisismystring(只有一个大写字母),那么我只想要
返回Thi

我已经尝试([A-Z]{1})([a-z]{2}){0,1}来获得我的匹配的第一次出现,如果有超过2个大写字母,但我不确定如何应用第二个条件。

5 个答案:

答案 0 :(得分:3)

您不能仅使用正则表达式执行此操作,因为匹配始终是输入的连续子字符串。你当然可以将几个匹配组合成一个最终结果。

String.Join(String.Empty, Regex.Matches(input, "[A-Z][a-z]{2}")
                               .Cast<Match>()
                               .Take(2)
                               .Select(match => match.Value));

答案 1 :(得分:1)

您可以创建一个这样的方法:

public string GetMyCharacters(string s)
        {
            int numOfCaps = Regex.Matches(s, "[A-Z]").Count;
            if (numOfCaps > 2)
            {
                var matches = Regex.Matches(s, "[A-Z][a-z]{2}");
                return matches[0].Value + matches[1].Value;
            }
            else if (numOfCaps == 1)
            {
                var matches = Regex.Matches(s, "[A-Z][a-z]{2}");
                return matches[0].Value;
            }
            else { return null; }
        }

然后这样称呼:

Console.WriteLine(GetMyCharacters("ThisisMystringItsTooLong")); // ThiMys
Console.WriteLine(GetMyCharacters("Thisismystring")); // Thi
Console.WriteLine(GetMyCharacters("wijfowro"));// null

答案 2 :(得分:1)

我只需使用正则表达式模式[A-Z][a-z]{2}并“手动”执行其他逻辑。

public string ShortIdentifier(string longIdentifier)
{
    MatchCollection matches = Regex.Matches(longIdentifier, "[A-Z][a-z]{2}");
    if (matches.Count == 1) {
        return matches[0].Value;
    } else if (matches.Count >= 2) {
        return matches[0].Value + matches[1].Value;
    }
    return longIdentifier.Substring(0, Math.Min(longIdentifier.Length, 6));
    // Or return whatever you want when there is no match.
}

如果要返回一个大写字母后跟一个或两个小写字母,请将正则表达式更改为[A-Z][a-z]{1,2}

答案 3 :(得分:1)

我最初误解了要求,但这是固定版本:

Regex.Replace(
    "ThisisMystringItsTooLong",
    "^(?:.*?([A-Z][a-z]{2}))?(?:.*?([A-Z][a-z]{2}))?.*$",
    "$1$2"
)

它匹配整个输入字符串,start(^)到end($),它分成:

(?:.*?([A-Z][a-z]{2}))? - optional non-capturing group, which consists of
                          a bunch of non-greedy anything followed
                          by substring sought, which is captured
(?:.*?([A-Z][a-z]{2}))? - another exactly same group; if we want to place
                          some limits on what can be between substrings
                          sought (like no spaces etc.) it goes here
                          instead of the anything
?.*                     - anything else

然后,它通过使用Regex.Replace方法连接两个(可能为空)匹配来构造输出字符串。经测试:

"ThisisMystringItsTooLong" -> "ThiMys"
"Thisismystring"           -> "Thi"
"thisismystring"           -> ""
"that is His String"       -> "HisStr"
"oh Hi There!"             -> "The"
"oh Hi There Go Here"      -> "TheHer"

与Danies的答案不同,除了正则表达式之外没有使用任何东西,但不确定它是否表现更好或更差。

答案 4 :(得分:0)

尝试

http://regex101.com/r/pU4aB5
([A-Z]{1}[a-z]{2})[a-z]*([A-Z]{1}[a-z]{2})?

然后你需要的是连接两个捕获组以获得最终结果。