简体   繁体   中英

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!

使用以下.. [ ]在正则表达式中具有特殊含义(字符类):

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

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.

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.

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