Reputation: 17368
I have 2 different words:
BB50AR-B0N5-001-UNI
F361424500
In the first case where -
is there, I want the first group as BB50AR-B0N5-001
i.e last group should not come
In the second case where -
is not there, I want the first group as F361424500
My attempt:
([\w]+)([-]?)(.*?)($)
The above regex is giving the reverse
Upvotes: 1
Views: 271
Reputation: 75840
Maybe one of these two options could help you out. If your pattern would always be the same two possible strings:
^\w+(-\w+){0,2}
Check the online demo
Or if you simply want to exclude the last part of a string if it's delimited:
^\w+$|.+(?=-)
Check the online demo.
Upvotes: 3
Reputation: 815
You can use: ^(.+?)(?:-[^-]+?)?$
With:
^
: beginning of the string(.+?)
: capturing group, with:
.+?
: any character, one or unlimited times, non greedy(?:-[^-]+?)?
: non capturing group, 0 or 1 time, with:
-[^-]+?
: a -
, anything excepted -
one or unlimited times, non greedy$
: end of the stringExample: https://regex101.com/r/D55yEL/3/
Upvotes: 3