[英]How to replace lower case with upper case using regular Expression?
我的字符串a帶有小寫字母。 我試圖使用以下表達式將小寫字母替換為大寫字母,但它並不能正常工作。 如何將字符串a中的小寫變成大寫?
using System.Text.RegularExpressions;
string a = "pieter was a small boy";
a = Regex.Replace(a, @"\B[A-Z]", m => " " + m.ToString().ToUpper());
您在這里有兩個問題:
\\b
而不是\\B
有關更多信息,請參見此問題 。 [AZ]
),因此您需要使用RegexOptions.IgnoreCase
來使代碼正常工作。 string a = "pieter was a small boy";
var regex = new Regex(@"\b[A-Z]", RegexOptions.IgnoreCase);
a = regex.Replace(a, m=>m.ToString().ToUpper());
上面代碼的輸出是:
Pieter Was A Small Boy
如果您嘗試將字符串中的所有字符都轉換為大寫,則只需執行string.ToUpper()
string upperCasea = a.ToUpper();
如果要進行不區分大小寫的替換,請使用Regex.Replace Method (String, String, MatchEvaluator, RegexOptions)
:
a = Regex.Replace(a,
@"\b[A-Z]",
m => " " + m.ToString().ToUpper(),
RegexOptions.IgnoreCase);
Regex.Replace(inputStr, @"[^a-zA-Z0-9_\\]", "").ToUpperInvariant();
它適合您:
string a = "pieter was a small boy";
a = a.ToUpper();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.