PT114
PT114

Reputation: 951

Parsing a regex for optional sections

Similar to this question but with a difference subtle enough that I still need some help.

Currently I have:

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

as my regex, which matches any number of characters followed by square brackets [] that contain two decimals separated by a dash. My issue is, I'd like it to also match with just one decimal number between the square brackets, and possibly even with nothing in between the square brackets. So:

word[1-5] = match
word[5] = match
word[] = match (not essential)

and ensuring

word[-5] = no match

Could anyone possibly point my in the direction of the next step. I currently find regex to be a bit of a guessing game though I would like to become better with them.

Upvotes: 0

Views: 98

Answers (4)

Emo Mosley
Emo Mosley

Reputation: 535

Not every regex interpreter supports this, but you could try an "or" operator for the part inside the brackets:

'(.*)\[(\d+\-\d+|\d+)\]'

Upvotes: 0

Javier Diaz
Javier Diaz

Reputation: 1830

(.*)\[((\d+(?:\-\d+)?)?)\]

This will match everything, even with 0 digits in there and will backreference you (in match[1-5]):

1- match 2- 1-5

Upvotes: 0

Anirudha
Anirudha

Reputation: 32797

Use ? to match 0 or 1 match

So use ? for the -\d+ and for both the digits separated by -

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

No need to escape -..It has special meaning only if its's between a character class.

Upvotes: 1

Gabber
Gabber

Reputation: 5452

Go with yours and make the last part optional

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

Using ?.

To accomplish the other task, well, go with ? again

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

A working example http://rubular.com/r/t0MaHyHfeS

Upvotes: 3

Related Questions