简体   繁体   中英

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

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 (ie \\s ) or till the end of the string is reached(ie $ )

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

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.

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

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