Home > OS >  How to get the substring of a matched string using regex
How to get the substring of a matched string using regex

Time:01-24

For example if I have a string:

This is a test for matching this

And I have used a regex to match ching in the above string then I how can extract out mat from the string matching?

Basically I need to match all occurrences of ching in a string and extract out anything that occurs before or after for that word and not till beginning or end of the entire string.

CodePudding user response:

Capturing letters before a fixed string "ching":

var matches = Regex.Matches(input, @"\b(?<x>\w )ching");

foreach(Match m in matches){
  Console.Write(m.Groups["x"].Value);
}

\w matches one or more word characters and captures them into a named group (?<x> ... )

If you want case insensitive matching, pass a RegexOptions.IgnoreCase as the third argument to Matches

  •  Tags:  
  • Related