Regex to get language matches

Viewed 64

I have the following input:

_YUE_ENSUB_L9939486_16X9

And I would like to match on YUE and EN. The conditions are:

  • Between two _, it only allows [A-Z419].
  • It should not include the suffix SUB, SUBS, or FN.

So far I have:

([A-Z419]+)(?:SUB|FN|SUBS)?

Or:

[A-Z419]{2,5}(?=SUB)

But both fall a bit short. What would be the correct regex for this? I suppose something like this perhaps but it seems a bit overkill and probably not a great match:

[A-Z419]+(?=SUB|FN|SUBS)|[A-Z419]+(?!=SUB|FN|SUBS)

Here are sample inputs from regex101.

2 Answers

You might use a capturing group and move the lookahead to right after the first underscore. Then match either SUB with an optional S or FN and an underscore.

_(?![A-Z419]*(?:SUBS?|FN)_)([A-Z419]+)_

Explanation

  • _ Match literally
  • (?! Negative lookahead, assert what is on the right does not match
    • [A-Z419]* Match 0+ times any of the listed chars
    • (?:SUBS?|FN)_ Match either SUB, SUBS or FN followed by _
  • ) Close lookahead
  • ( Capture group 1
    • [A-Z419]+ Match 1+ times any of the listed chars
  • )_ Close group and match an underscore

Regex demo

For the updated question, you could get the matches only:

(?<=_)[A-Z419]+?(?=(?:SUBS?|FN)?_)

Explanation

  • (?<=_) Positive lookbehind, assert what is directly to the left is _
  • [A-Z419]+? Match one of the listed char, as least as possible
  • (?= Positive lookahead, assert what is directly to the right
    • (?:SUBS?|FN)?_ Optionally match SUB, SUBS or FN followed by _
  • ) Close lookahead

Regex demo

Search for:

^_([^_]*)_([^_]*)(SUB|SUBS|FN)

You have the languages in capture groups 1 and 2.

Test here.


For the updated question:

Regex:

_([A-Z419]*?)(SUB|SUBS|FN)?(?=_)

Languages are in capture group 1.

Test here.

Related