简体   繁体   中英

Is there a lowercase expression for .Net regular expressions?

Perl has the \\u operator to lowercase a match when using string replacement and regular expressions. Does .Net have anything similar? For example, uppercase all words that start with a <

s/<\(\w*\)/<\U\1/

The way to do these kind of things in .NET is using the MatchEvaluator parameter:

string pattern = @"<(\w*)";
string replaced = Regex.Replace(line, pattern, 
                  x => "<" + x.Groups[1].ToString().ToUpper());     

This reads: Whenever you find the regular expression, replace it with the first group uppercased.

You've got some errors in your Perl code. In both Perl and .NET regexes, \\( and \\) match the literal characters, ( and ) ; to use parentheses as grouping operators, leave the backslashes off. Also, \\u\u003c/code> does not lowercase a match , it titlecases (usually the same as uppercasing) the next character . What you're thinking of is \\L , which lowercases all characters until the end of the string or \\E , whichever comes first.

In Perl, \\U , \\L and such aren't really a regex feature, they're a string feature, like the more common escape sequences: \\n , \\t , etc.. They're listed redundantly in the regex docs because they're especially useful in regex substitutions. C# has no equivalent for them, either in string literals or the regex classes, but as @steinar pointed out, it does have MatchEvaluator and (since .NET 3.0) lambda expressions:

string s = "ABC<XYZ!";
Console.WriteLine(Regex.Replace(s, @"<(\w+)", m => m.Value.ToLower()));

output:

ABC<xyz!

edit: The parentheses aren't really necessary in my example, but I left them in to demonstrate their proper use as grouping operators. I also changed the original \\w* to \\w+ ; there's no point matching zero word characters when your only goal is to change the case of word characters.

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