简体   繁体   中英

How to replace lower case with upper case using regular Expression?

I have the string a with full of lower case. I tried to use the following Expression to replace lower case with upper case but it does not work as I want. How can I turn the lower case into upper case in string a?

using System.Text.RegularExpressions;

string a = "pieter was a small boy";
a = Regex.Replace(a, @"\B[A-Z]", m => " " + m.ToString().ToUpper());

You have two problems here:

  1. Your pattern needs to use \\b instead of \\B . See this question for more info.
  2. Since your string is in lowercase and your pattern only matches uppercase ( [AZ] ) you need to use RegexOptions.IgnoreCase to make your code work.

string a = "pieter was a small boy";
var regex = new Regex(@"\b[A-Z]", RegexOptions.IgnoreCase);
a = regex.Replace(a, m=>m.ToString().ToUpper());

The output of the above code is:

Pieter Was A Small Boy

If you are trying to convert all the characters in the string to upper case then simply do string.ToUpper()

string upperCasea = a.ToUpper();

If you want to do a case insensitive replace then use Regex.Replace Method (String, String, MatchEvaluator, RegexOptions) :

a = Regex.Replace(a, 
                  @"\b[A-Z]", 
                  m => " " + m.ToString().ToUpper(), 
                  RegexOptions.IgnoreCase);

Using Regular Expression as you wanted,

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

Source

Regex.Replace(inputStr, @"[^a-zA-Z0-9_\\]", "").ToUpperInvariant();

It works fine for you :

string a = "pieter was a small boy";
a = a.ToUpper();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM