Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the substring of a matched string using regex

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

This 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading