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

Regex to match words between underscores after second occurence of underscore

so i would like to get words between underscores after second occurence of underscore

this is my string

ABC_BC_BE08_C1000004_0124

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

I’ve assembled this expresion

(?<=_)[^_]+

well it matches what i need but only skips the first word since there is no underscore before it. I would like it to skip ABC and BC and just get the last three strings, i’ve tried messing around but i am stuck and cant make it work. Thanks!

>Solution :

You can use a non-regex approach here with Split and Skip:

var text = "ABC_BC_BE08_C1000004_0124";
var result = text.Split('_').Skip(2);
foreach (var s in result)
    Console.WriteLine(s);

Output:

BE08
C1000004
0124

See the C# demo.

With regex, you can use

var result = Regex.Matches(text, @"(?<=^(?:[^_]*_){2,})[^_]+").Cast<Match>().Select(x => x.Value);

See the regex demo and the C# demo. The regex matches

  • (?<=^(?:[^_]*_){2,}) – a positive lookbehind that matches a location that matches the following patterns immediately to the left of the current location:
    • ^ – start of string
    • (?:[^_]*_){2,} – two or more ({2,}) sequences of any zero or more chars other than _ ([^_]*) and then a _ char
  • [^_]+ – one or more chars other than _
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