Martyn Ball
Martyn Ball

Reputation: 4885

Regex multiple groups, first group not include last group

I need to match any word after the LAST _ within a string, then match everything before that minus the _.

So test_test_DAY would return: [ 'test_test', 'DAY' ].

This is what I have at the moment, which works spot on for the DAY section.

([^\_]+$)

Upvotes: 1

Views: 466

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

The pattern ([^\_]+$) captures in a single group matching 1+ times not an underscore.

You might use 2 capturing groups:

^(.*)_(.*)$

If there must be at least 1 char before and after the _ you could change the quantifier to + instead of *

Regex demo

If the pattern should take matching the underscores into account where there can not be 2 consecutive underscores, you might use 2 capturing groups with a repeating group:

^([^_]+(?:_[^_]+)*)_([^_]+)$
  • ^ Start of string
  • ( Capture group 1
    • [^_]+ Negated character class, match 1+ times any char except _
    • (?:_[^_]+)* Repeat 0+ times matching _ followed by any char except _
  • ) Close group 1
  • _ Match literally
  • ( Capture group 2
    • [^_]+ Match 1+ times any char except _
  • ) Close group 2
  • $ End of string

Regex demo

Upvotes: 1

Related Questions