[英]How I can replace [city] to [City] in string
我想替換[city], [cIty], [ciTY], ...
與[City]
。
我認為正則表達式是一個很好的解決方案,但我不擅長正則表達式。
試過的代碼:
var text = "[City] [CIty] [ciTY] [city] [CITy]";
if (text.Contains("[city]"))
{
//text = text.Replace("[city]", "[City]");
text = Regex.Replace(text, @"[city]", "[City]");
textbox.Text = text;
textbox.SelectionStart = textbox.Text.Length;
textbox.SelectionLength = 0;
}
除了輸出
[市] [市] [市] [市] [市]
這是行不通的,因為regex
語法沒有完成
三點:
要匹配文本中的括號[]
,您需要在正則表達式中對它們進行轉義: @"\\[city\\]"
在Regex.Replace
添加忽略大小寫RegexOptions.IgnoreCase
的選項
對於“包含”,它不使用正則表達式。 請改用Regex.IsMatch
。
所以這會將你的問題中的代碼變成這樣:
var text = textbox.Text;
var pattern = @"\[City\]";
// Will match [city], [cITy], [CITY], but not exactly [City]
if (Regex.IsMatch(text, pattern, RegexOptions.IgnoreCase) && !Regex.IsMatch(text, pattern))
{
text = Regex.Replace(text, pattern, "[City]", RegexOptions.IgnoreCase);
// same code after that
}
您需要對括號進行轉義,使用Regex.IsMatch
而不是Contains
,並使模式區分大小寫。 您可以在 regex 模式中執行此操作,但 C# 內置了RegexOptions
因此您可以IgnoreCase
。 這是它的樣子:
if(Regex.IsMatch(text, @"\[city\]", RegexOptions.IgnoreCase))
{
text = Regex.Replace(text, @"\[city\]", "[City]", RegexOptions.IgnoreCase);
}
這是一個dotnetfiddle
您需要對正則表達式中的括號等特殊字符進行轉義,您可以在下面的模式字符串中看到這些字符。 然后,您需要添加正則表達式選項 RegexOptions.IgnoreCase 以在將字符串與模式字符串進行比較時忽略大小寫。
var testText = @"[CIty] [ciTY] [city] [CITy] [City]";
Console.WriteLine("Original text: " + testText);
var pattern = @"\[City\]";
if(Regex.IsMatch(testText, pattern, RegexOptions.IgnoreCase))
{
//use the below updated value as you wish
var updatedStringVal = Regex.Replace(testText, pattern, "[City]", RegexOptions.IgnoreCase);
Console.WriteLine("Updated text: " + updatedStringVal);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.