0

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());
5
  • 5
    is a.ToUpper() not enough??? Commented Nov 16, 2012 at 11:22
  • What are you trying to do ? convert whole string to upper case ? Commented Nov 16, 2012 at 11:26
  • 1
    I think OP gone through this link and cant invert the solution for ToUpper(). Commented Nov 16, 2012 at 11:30
  • a.ToUpper() can solve the problem i guess Commented Nov 16, 2012 at 11:54
  • 1
    All the people who downvoted because "a.ToUpper() is not enough??" need to open their minds a little bit beyond the use case posted here. I came to this post from Google because I'm writing a source code conversion utility and I need a regex that will find a declaration, then a property accessor, then the first following character and upper-case it. No, ToUpper is not good enough. Commented Dec 19, 2014 at 5:01

5 Answers 5

11

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 ([A-Z]) 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
Sign up to request clarification or add additional context in comments.

1 Comment

"two problems" heh heh
3

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);

1 Comment

This doesn't answer the question. He specifically asks for the use case of a regex. I think that would automatically imply that he wants to ToUpper on a capture group, or at least something to do with regex.
0

Using Regular Expression as you wanted,

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

Source

3 Comments

That regex adds space as well. That isn't what the OP wants
removed the space, is it ok now? @Cthulhu
You need to change the \B to \b, too.
-1

It works fine for you :

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.