GeneralBear
GeneralBear

Reputation: 1021

Capturing first group and separately third + fourth group (REGEX)

I'm trying to create two separate regexes that capture two specific parts of a string:

Example string: 3027-20171110020655-test-5

I need to capture first: 3027 and second: test-5 The second group may not always have a hyphen in it.

I have so far created: [^\-]+ This creates 4 separate capture groups -- I'm not sure how to narrow it down further.

Upvotes: 0

Views: 144

Answers (2)

anubhava
anubhava

Reputation: 785156

You can use this regex using negated character classes and anchors:

^([^-]+)-[^-]*-([^-]+)(?:-([^-]+))?$

Where last group is an optional match.

RegEx Demo

Upvotes: 0

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

Add the ^ token to mark the beginning of the string:

^[^\-]+

Then, depending on how your input is formatted, you don't need separate regex's, just put whatever you are trying to capture into capturing groups, using parentheses (())

^([^\-]+)-\d+-(.*)

Test it here

Upvotes: 1

Related Questions