Valentin Radu
Valentin Radu

Reputation: 649

Replace with wildcards

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").

Upvotes: 9

Views: 26316

Answers (3)

Anirudha
Anirudha

Reputation: 32807

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 (.*?)

Upvotes: 13

Mitch
Mitch

Reputation: 22271

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");

Upvotes: 7

Martin Ender
Martin Ender

Reputation: 44269

The problem with your attempt is, that it cannot know that the replacement string should be inserted after your variable. Let's assume that valid variable names contain letters, digits and underscores (which can be conveniently matched with \w). That means, any other character ends the variable name. Then you could match the variable name, capture it (using parentheses) and put it in the replacement string with $1:

output = Regex.Replace(input, @"Read\s+(\w+)", "$1 = MessageBox.Show");

Note that \s+ matches one or more arbitrary whitespace characters. \w+ matches one or more letters, digits and underscores. If you want to restrict variable names to letters only, this is the place to change it:

output = Regex.Replace(input, @"Read\s+([a-zA-Z]+)", "$1 = MessageBox.Show");

Here is a good tutorial.

Finally note, that in C# it is advisable to write regular expressions as verbatim strings (@"..."). Otherwise, you will have to double escape everything, so that the backslashes get through to the regex engine, and that really lessens the readability of the regex.

Upvotes: 5

Related Questions