简体   繁体   中英

How to replace words following certain character and extract rest with REGEX

Assume that i have the following sentence

select PathSquares from tblPathFinding where RouteId=470 
and StartingSquareId=267 and ExitSquareId=13

Now i want to replace words followed by = and get the rest of the sentence

Lets say i want to replace following word of = with %

Words are separated with space character

So this sentence would become

select PathSquares from tblPathFinding where RouteId=%
and StartingSquareId=% and ExitSquareId=%

With which regex i can achieve this ?

.net 4.5 C#

Use a lookbehind to match all the non-space or word chars which are just after to = symbol . Replacing the matched chars with % wiil give you the desired output.

@"(?<==)\S+"

OR

@"(?<==)\w+"

Replacement string:

%

DEMO

string str = @"select PathSquares from tblPathFinding where RouteId=470 
and StartingSquareId=267 and ExitSquareId=13";
string result = Regex.Replace(str, @"(?<==)\S+", "%");
Console.WriteLine(result);

IDEONE

Explanation:

  • (?<==) Asserts that the match must be preceded by an = symbol.
  • \\w+ If yes, then match the following one or more word characters.

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