[英]How to capitalize 1st letter (ignoring non a-z) with regex in c#?
關於如何用C#將首字母大寫的文章很多,但是當我忽略其中的帶前綴的非字母字符和標簽時,我特別在努力做到這一點。 例如,
<style=blah>capitalize the word, 'capitalize'</style>
如何忽略潛在的 <>標記(或之前的非字母字符,例如星號*
)及其中的內容,然后大寫“大寫”?
我試過了:
public static string CapitalizeFirstCharToUpperRegex(string str)
{
// Check for empty string.
if (string.IsNullOrEmpty(str))
return string.Empty;
// Return char and concat substring.
// Start @ first char, no matter what (avoid <tags>, etc)
string pattern = @"(^.*?)([a-z])(.+)";
// Extract middle, then upper 1st char
string middleUpperFirst = Regex.Replace(str, pattern, "$2");
middleUpperFirst = CapitalizeFirstCharToUpper(str); // Works
// Inject the middle back in
string final = $"$1{middleUpperFirst}$3";
return Regex.Replace(str, pattern, final);
}
編輯:
輸入: <style=foo>first non-tagged word 1st char upper</style>
預期輸出: <style=foo>First non-tagged word 1st char upper</style>
使用后置正則表達式功能,您可以在不帶括號的情況下匹配第一個“大寫”,然后可以將輸出大寫。
正則表達式如下:
(?<=<.*>)\w+
它會與>括號后的第一個單詞匹配
您可以使用
<[^<>]*>|(?<!\p{L})(\p{L})(\p{L}*)
正則表達式執行以下操作:
<[^<>]*>
-匹配<
,除<
和>
以外的任何0+字符,然后匹配>
|
- 要么 (?<!\\p{L})
-查找未緊跟字母開頭的位置 (\\p{L})
-將任何字母捕獲到組1中 (\\p{L}*)
-將任何0+個字母捕獲到第2組中(如果要小寫單詞的其余部分,這是必需的)。 然后,檢查第2組是否匹配,如果是,則將第一個組值大寫,將第二個組小寫,否則返回整個值:
var result = Regex.Replace(s, @"<[^<>]*>|(?<!\p{L})(\p{L})(\p{L}*)", m =>
m.Groups[1].Success ?
m.Groups[1].Value.ToUpper() + m.Groups[2].Value.ToLower() :
m.Value);
如果您不需要小寫其余單詞,請刪除第二組以及與此相關的代碼:
var result = Regex.Replace(s, @"<[^<>]*>|(?<!\p{L})(\p{L})", m =>
m.Groups[1].Success ?
m.Groups[1].Value.ToUpper() : m.Value);
要僅使用此方法替換第一次出現的情況,您需要設置一個標志並在找到第一個匹配項后將其反轉:
var s = "<style=foo>first non-tagged word 1st char upper</style>";
var found = false;
var result = Regex.Replace(s, @"<[^<>]*>|(?<!\p{L})(\p{L})", m => {
if (m.Groups[1].Success && !found) {
found = !found;
return m.Groups[1].Value.ToUpper();
} else {
return m.Value;
}
});
Console.WriteLine(result); // => <style=foo>First non-tagged word 1st char upper</style>
參見C#演示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.