regExNewb
regExNewb

Reputation: 3

Regular Expression to match dimension specification

I need some help writing a regular expression that matches this:

Example matches:

Not matches:

Upvotes: 0

Views: 251

Answers (1)

Richard Cook
Richard Cook

Reputation: 33109

Assuming that "numbers" are one or more occurrences of the digit class \d, one regular expression would be:

^\d+(,\d+)+$|^\[\d+(,\d+)+\]$

Other variants of "numbers" might be [1-9][0-9]* which would not allow leading zeroes and would be closer to the C/C++/C#/Java representation of a decimal integer literal. Leading zeroes in C/C++/C#/Java, for example, designate octal integer literals. In Java, I believe that 0 is officially a decimal literal so a more accurate expression would be 0|[1-9][0-9]* while in C++ 0 is technically an octal literal (I think!).

Assuming Java-style integer literals, our expression would then become:

^(0|[1-9][0-9]*)(,(0|[1-9][0-9]*)+)+$|^\[(0|[1-9][0-9]*)+(,(0|[1-9][0-9]*)+)+\]$

Whatever you do, you need to decide what constitutes "number" in your situation which may or may not be the same as the programming language you are implementing your program in.

Useful links:

Upvotes: 1

Related Questions