tags:

views:

42

answers:

2

Need a regex that will match either of {m,n}|{m,}|{,n}|{n} (where m and n are integer numbers) with arbitrary number of spaces in between symbols in the beginning of the line. I came up with this:

^({\s*\d+\s*,\s*\d+\s*}|{\s*,\s*\d+\s*}|{\s*\d+\s*,\s*}|{\s*\d+\s*})

While it certainly works, I was curious if there is a way to make it shorter. Thanks for input.

UPDATE: Mark proposed an excellent solution: ^\{(\s*\d+\s*(,(\s*\d+\s*)?)?|,\s*\d+\s*)\}

+1  A: 

You should be able to do this, at the very least (ignoring spaces for now for brevity):

"^\\{(\\d+(,(\\d+)?)?|,\\d+)\\}"

This captures all but the {,n} case in the first alternative.

Adding spaces back in:

"^\\{\\s*(\\d+(\\s*,(\\s*\\d+)?)?|,\\s*\\d+)\\s*\\}"

May not look shorter but remember I'm properly escaping things for Java where you are certainly not.

Mark Peters
you are missing a closing bracket - ^{(\d+(,(\d)?)?)|,\d+}. Thanks, this is the level of brevity I was looking for :)
Nick
I think it's fixed by now Nick. Sorry about so many edits.
Mark Peters
A: 

For one, they all start with {\s* and end with \s*}. So you can at least "refactor those out:

^{\s*(\d+\s*,\s*\d+|,\s*\d+|\d+\s*,|\d+)\s*}

z5h