Ok so I'm the absolute worst regular expression writer on the planet. Figured this great commu开发者_如何转开发nity could help me out after 15 minutes of bashing my head off the desk and getting nowhere.
I know this is simple, but I need a regular expression that matches the conditions of:
SomeWord_SomeSecondWord
or
SomeWord_SomeSecondWord_SomeThirdWord
In plain english:
- two or three words (set of letters) separated by underscores.
- Each word block must start with a capital letter, contain at least two characters and contain only letters a-z.
Any help would be greatly appreciated. I'm trying to write a regular expression to match unit testing method names for StyleCop/ReSharper validation. I have an absolute mental block when it comes to regex.
Try this:
@"^[A-Z][a-zA-Z]+(?:_[A-Z][a-zA-Z]+){1,2}$"
The [A-Z][a-zA-Z]+
ensures it starts with a capital letter, and the usage of +
will ensure at least one other character, which satisfies the requirement of the 2 character minimum.
Here's an example of it in action:
string[] inputs =
{
"SomeWord", "SomeFirstWord_SomeSecondWord",
"SomeWord_SomeSecondWord_SomeThirdWord", "SomeWord_Some2ndWord"
};
string pattern = @"^[A-Z][a-zA-Z]+(?:_[A-Z][a-zA-Z]+){1,2}$";
foreach (var input in inputs)
{
Console.WriteLine("{0}: {1}", Regex.IsMatch(input, pattern), input);
}
精彩评论