[英]Regex match first two occurrences of a capital letter followed by several lower case
我一直在通过此处的示例查看如何进行类似的正则表达式匹配,但是我无法使其适合我的情况。
我有一个类似ThisisMystringItsTooLong
的字符串,我想找回ThiMys
( 前两个大写字母,然后是两个小写字母 ),但是,如果该字符串只是Thisismystring
(只有一个大写字母),那么我只是想
退Thi
我尝试过([AZ]{1})([az]{2}){0,1}
仅在匹配的大写字母超过2个的情况下才第一次出现我的匹配项,但是我我不确定如何应用第二个条件。
您不能仅使用正则表达式来做到这一点,因为匹配始终是输入的连续子字符串。 您当然可以将多个匹配项组合为一个最终结果。
String.Join(String.Empty, Regex.Matches(input, "[A-Z][a-z]{2}")
.Cast<Match>()
.Take(2)
.Select(match => match.Value));
您可以创建这样的方法:
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
我将只使用Regex模式[AZ][az]{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.
}
如果要返回一个大写字母,然后返回一个或两个小写字母,请将正则表达式更改为[AZ][az]{1,2}
。
我最初误解了需求,但是这里是固定版本:
Regex.Replace(
"ThisisMystringItsTooLong",
"^(?:.*?([A-Z][a-z]{2}))?(?:.*?([A-Z][a-z]{2}))?.*$",
"$1$2"
)
它与整个输入字符串匹配,从开始(^)到结束($),它将分为以下部分:
(?:.*?([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的答案不同,它除了使用正则表达式外没有使用其他任何东西,但是不确定它的性能是好是坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.