Home > Net >  RegEx how I can find these 3 groups?
RegEx how I can find these 3 groups?

Time:06-22

I have a string with three different texts inside the exact line, separated by a _

I want a regex to extract the first part of the data, a regex for the second, and one for the last part.

The string is like xxxxxx_yyyyyyy_zzzzzz (where x, y, and z it's random data).

I have tried this:

^[^_]*

But I can only figure out how to match the first part of the data for x.

CodePudding user response:

You haven't given us what programming language you are using regex from. But, generally, this is what you want:

^([^_] )_([^_] )_([^_] )$

The parenthesis are "capturing groups" which can then be referred to as \x, $x, some other way where x is 1, 2 or 3. That depends on your regex implementation and programming language. Using your example string, \2 would be yyyyyyy.

CodePudding user response:

As alternative, you can use positive look-ahead (?=) and positive look-behind (?<=) capture groups like this:

(?<=_|^)\d (?=$|_)

This is relatively safe RegExp, as long as original string only contain numbers.

Explanation and examples: https://regex101.com/r/ZptWHV/1

  • Related