Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace with wildcards

Tags:

c#

regex

I need some advice. Suppose I have the following string: Read Variable I want to find all pieces of text like this in a string and make all of them like the following:Variable = MessageBox.Show. So as aditional examples:

"Read Dog" --> "Dog = MessageBox.Show"
"Read Cat" --> "Cat = MessageBox.Show"

Can you help me? I need a fast advice using RegEx in C#. I think it is a job involving wildcards, but I do not know how to use them very well... Also, I need this for a school project tomorrow... Thanks!

Edit: This is what I have done so far and it does not work: Regex.Replace(String, "Read ", " = Messagebox.Show").

like image 879
Valentin Radu Avatar asked Nov 18 '12 17:11

Valentin Radu


2 Answers

You can do this

string ns= Regex.Replace(yourString,"Read\s+(.*?)(?:\s|$)","$1 = MessageBox.Show");

\s+ matches 1 to many space characters

(.*?)(?:\s|$) matches 0 to many characters till the first space (i.e \s) or till the end of the string is reached(i.e $)

$1 represents the first captured group i.e (.*?)

like image 143
Anirudha Avatar answered Sep 29 '22 09:09

Anirudha


You might want to clarify your question... but here goes:

If you want to match the next word after "Read " in regex, use Read (\w*) where \w is the word character class and * is the greedy match operator.

If you want to match everything after "Read " in regex, use Read (.*)$ where . will match all characters and $ means end of line.

With either regex, you can use a replace of $1 = MessageBox.Show as $1 will reference the first matched group (which was denoted by the parenthesis).

Complete code:

replacedString = Regex.Replace(inStr, @"Read (.*)$", "$1 = MessageBox.Show");
like image 30
Mitch Avatar answered Sep 29 '22 11:09

Mitch