user979331
user979331

Reputation: 11871

C# ASP.NET Reg Replace...Replace string with another string

I have this string here

string Thing1 = "12340-TTT";

string Thing2 = "®"

I am looking to use reg replace to replace the TTT with &reg.

I am told using reg replace it does not matter if its uppercase or lowercase.

How would I go about doing this?

Upvotes: 1

Views: 706

Answers (5)

Ben McDougall
Ben McDougall

Reputation: 251

Try this:

    string one = "1234-TTT";

    string pattern = "TTT";
    Regex reg = new Regex(pattern);
    string two = "&reg";
    string result = reg.Replace(one, two);
    Console.WriteLine(result);

should give you the desired Result. And just for a good read if you should ever need some more complicated Regular Expressions: http://msdn.microsoft.com/en-us/library/vstudio/xwewhkd1.aspx

Upvotes: 2

Giorgio Minardi
Giorgio Minardi

Reputation: 2775

Also, between the RegexOptions you can pass to the regex there is the IgnoreCase to make it case insensitive:

string Thing1 = "12340-TTT";
string Thing2 = "®"
var regex = new Regex("TTT", RegexOptions.IgnoreCase );
var newSentence = regex.Replace( Thing1 , Thing2  );

Upvotes: 0

valverij
valverij

Reputation: 4941

For this, you can use the Regex.Replace method (documentation here)

There are several overloaded versions, but the most direct one for this is the Regex.Replace(String input, String regexPattern, String replacementString) version:

string Thing1 = "12340-TTT";
string Thing2 = "®";

string newString =  System.Text.RegularExpressions.Regex.Replace(Thing1, "[Tt]{3}", Thing2);

If you are unfamiliar with regular expressions, the [Tt] define specific character group (any characters matching one of ones specified) and the {3} just indicates that it must be appear 3 times. So, this will do a case-insensitive search for a string of 3 T's (e.g., TTT, ttt, TtT, tTt, etc.)

For more on basic regex syntax, you can look here: http://www.regular-expressions.info/reference.html

Upvotes: 0

spy890
spy890

Reputation: 101

string input = "12340-TTT";
string output = Regex.Replace(input, "TTT", "&reg");

// Write the output.
Console.WriteLine(input);
Console.WriteLine(output);
Console.ReadLine();

This should do the trick. You find "TTT" in a string and replace it with "&reg".

Upvotes: 3

mCube
mCube

Reputation: 342

correct me if i'm wrong but i think it is same with that of replacing a string on a variable like this: string Thing1 = "12340-TTT";

string Thing2 = Regex.Replace(Thing1 , "®", "anyString");

got it from here:

http://www.dotnetperls.com/regex-replace

cheers:)

Upvotes: 1

Related Questions