简体   繁体   中英

Regex replace - forming the replacement string based on the match string c#

I want to preform replacements like replacing:

declare @whatever int;

with

declare @whatever int = 42;

I can match the desired string parts with...

@"(declare)(\s+)" + myVar + @"(\s+)(\w+)(\s*)(;)"

But I am not sure of a good create the replacement.

You can use Regex replacement to match on your pattern and replace it with your desired text. I recommend taking advantage of groups for this.

Example Regex: "declare\\s[@]\\w+\\s\\w+(?<value>\\s=\\s.+)?;"

You can now replace the regex group "value" with " = 42".

Unfortunately that group won't exist in your case, so you will have to insert it. You can do this by grouping and matching on the surrounding text and replace that text. These are just some ideas to help you.

These references will also help:

Check this:

string input =
@"declare p1 int;
declare p2 int;";
string result = Regex.Replace(input, @"declare\s+\w+\s+int\s*", "$0=33");
//result:
//declare p1 int=33;
//declare p2 int=33;

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