Jam
Jam

Reputation: 339

Replacing characters within a text with regex in c#

I am trying to replace few characters from a text. These characters maybe from start or end or it may be in middle. The problem is that it hasn't any white space at starting or ending. For example i want to replace "text" from this text with, for instance, "abc".

input: Thisisatextbox

output: Thisisaabcbox

I tried this code so far.

Regex.Replace(textBox.Text, @"\w[text]", "abc");

Any help would be appreciated. Thanks!

Upvotes: 1

Views: 180

Answers (3)

Rakshith Ravi
Rakshith Ravi

Reputation: 385

Wouldn't a simple Replace function work? I don't believe Regex is required.
Try this :

string oldText = "Thisisatextbox";
string newText = oldText.Replace("text", "abc");

I believe this would be easier.

Upvotes: 1

Anshul Rai
Anshul Rai

Reputation: 782

Regex.Replace(textBox.Text, @"\w*(text)\w*", "abc");

Use parentheses to capture the text you want to replace.

[] describes a character class. So, if you put [text] it will take ONE character from "t", "x", "e" to search for a possible match.

Upvotes: 0

karthik manchala
karthik manchala

Reputation: 13640

Use the following.. [ ] has special meaning (character class) in regex:

Regex.Replace(textBox.Text, @"text", "abc");

Upvotes: 2

Related Questions