Lars Nielsen
Lars Nielsen

Reputation: 436

regex opltional matching groups

Hi im trying to create a regex for the following expression

I need matching groups on all the integers

So the first part would be like

^(\d+)-(\d+)

which matches 1-50

With these matching groups

what do i need to add to the second part to make

/integer

optional but / should not be in the 3rd matching group and an integer is supplied

Upvotes: 0

Views: 53

Answers (2)

Barmar
Barmar

Reputation: 780724

Put the slash inside a non-capturing group, and the number after it in a capture group.

^(\d+)-(\d+)(?:/(\d+))?

Upvotes: 1

pascalhein
pascalhein

Reputation: 5846

Use a non-capturing optional group, and inside it the integer group.

This should work for you:

^(\d+)-(\d+)(?:/(\d+))?$

Upvotes: 1

Related Questions