0

I'm trying to improve a code using RegEx. Basically I have some patterns and I need to replace with the same pattern but using uppercase.

For example:

".a."

to

".A."

another pattern

"'a"

to

"'A"

I know a little bit about regex, but I don't know to replace to the same content but on uppercase.

2 Answers 2

2

As Cyral said:

var str = "hello.a.world";
str = Regex.Replace(str, @'\.[a-z]\.', x => x.Value.ToUpper());
//str == "hello.A.world"

This tutorial is a great reference for .NET's regular expression engine and regular expressions in general.

Expresso is a fantastic tool that I use frequently when I work with regular expressions. It will spell out what the regular expression does, and allows you to test it out on sample text. It also uses the same regex engine as .NET, so if your expression works in Expresso, it will work in C#.

Edit: Just to be clear, Cyral's answer is correct, I just wanted to be sure to add these links on to the page, as they are very helpful.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow I didn't see the lambda on his answer. Thanks.
0

You don't need to use regex, you can just use String.ToUpper

string str = ".a.";
str = str.ToUpper();

EDIT: To replace only from a pattern, run a function on the match: (Where [a-z] is your own regex)

str = Regex.Replace(str, @"[a-z]", s => s.Value.ToUpper());

4 Comments

I can't, I need to replace only when match the pattern, the rest should keep lowercase.
@ThiagoCustodio I have added another idea
I won't work. It's a kind of abreviation. I should keep lower case the full string. Only transform to uppercase when match those patterns. Thanks for your help.
Create a Regex for that and plug it into my code and it will work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.