使用RegEx对字符串进行大写和小写 [英] Use RegEx to uppercase and lowercase the string
问题描述
我正在尝试根据索引将字符串转换为大写和小写.
I am trying to convert a string to uppercase and lowercase based on the index.
我的字符串是一个 LanguageCode
,例如 cc-CC
,其中 cc
是语言代码,而 CC
是国家代码.用户可以以"cC-Cc"之类的任何格式输入.我正在使用正则表达式来匹配数据是否为 cc-CC
格式.
My string is a LanguageCode
like cc-CC
where cc
is the language code and CC
is the country code. The user can enter in any format like "cC-Cc". I am using the regular expression to match whether the data is in the format cc-CC
.
var regex = new Regex("^[a-z]{2}-[A-Z]{2}$", RegexOptions.IgnoreCase);
//I can use CultureInfos from .net framework and compare it's valid or not.
//But the requirement is it should allow invalid language codes also as long
//The enterd code is cc-CC format
现在,当用户输入 cC-Cc
时,我尝试先将小写的前两个字符小写,然后将大写的后两个字符小写.
Now when the user enters something cC-Cc
I'm trying to lowercase
the first two characters and then uppercase
last two characters.
我可以使用-
分割字符串,然后将它们连接起来.
I can split the string using -
and then concatenate them.
var languageDetails = languageCode.Split('-');
var languageCodeUpdated = $"{languageDetails[0].ToLowerInvariant()}-{languageDetails[1].ToUpperInvariant()}";
我想我可以避免创建多个字符串,而是使用 RegEx
本身相应地将大小写转换为大写和小写.
I thought can I avoid multiple strings creation and use RegEx
itself to uppercase and lowercase accordingly.
在搜索相同内容时,我发现了一些使用 \ L
和 \ U
的解决方案,但是我无法将它们用作 C#
编译器显示错误.另外, RegEx.Replace()
具有一个我无法理解的参数或委托 MatchEvaluator
.
While searching for the same I found some solutions to use \L
and \U
but I am not able to use them as the C#
compiler showing error. Also, RegEx.Replace()
has a parameter or delegate MatchEvaluator
which I'm not able to understand.
在 C#
中有什么方法可以使用 RegEx
将大写字母替换为小写字母,反之亦然.
Is there any way in C#
we can use RegEx
to replace uppercase with lowercase and vice versa.
推荐答案
.NET regex不支持大小写修改运算符.
.NET regex does not support case modifying operators.
您可以使用 MatchEvaluator
:
var result = Regex.Replace(s, @"(?i)^([a-z]{2})-([a-z]{2})$", m =>
$"{m.Groups[1].Value.ToLower()}-{m.Groups[2].Value.ToUpper()}");
请参见 C#演示.
详细信息
-
(?i)
-RegexOptions.IgnoreCase
mopdiofier 的嵌入式版本 -
^
-字符串的开头 -
([[a-z] {2})
-捕获组#1:2个ASCII字母 -
-
-连字符 -
([[a-z] {2})
-捕获组2:2个ASCII字母 -
$
-字符串的结尾.
(?i)
- the inline version ofRegexOptions.IgnoreCase
mopdiofier^
- start of the string([a-z]{2})
- Capturing group #1: 2 ASCII letters-
- a hyphen([a-z]{2})
- Capturing group #2: 2 ASCII letters$
- end of string.
这篇关于使用RegEx对字符串进行大写和小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!