簡體   English   中英

如何使用正則表達式將小寫字母替換為大寫字母?

[英]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());

您在這里有兩個問題:

  1. 您的模式需要使用\\b而不是\\B 有關更多信息,請參見此問題
  2. 由於您的字符串是小寫字母,並且您的模式僅匹配大寫字母( [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);

根據需要使用正則表達式,

a = Regex.Replace(a, @"\b[a-z]", m => m.ToString().ToUpper());

資源

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM