Hey StackExchange
Hey StackExchange

Reputation: 2125

Java RegExp for a separated group of digits

I'm trying to write a regexp validating: one (or more) group of digits between 1 and 99 separated by | or , (both can be combined)

Example

Must accept:

1
10
1,2,3|5|10,20|30
1|5

Must refuse:

1,
10,,
1,2,3!5

For the group of digits, its straight forward: [1-9][0-9]. For the rest, its a mystery (still).

Question

Can someone assist proposing the correct regexp ?

Upvotes: 0

Views: 87

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12668

\d([,|]?\d)*

is a possible candidate for your expressión, it means the repetition of at least one or more digits, separated (optionally ---the ? after [,|] means optional) by any character from the set of { ',', '|' }.

Proof:

  • the interdigit separator is optional, so any number of digits can be between two separators. This allows for sequences of digits of any length.
  • there must be a maximum of one separator between digits (separator is optional, but must be followed by a digit).
  • As the regexp begins with a digit, and forcedly ends in one, no acceptable , or | at the beginning or the end of the string.

See demo to test it.

Note

If you'd like to accept it on a line by line basis, rejecting things that begin or end with the separator chars, just anchor the regexp to beginning/end of the line with ^ and $. As in demo2.

^\d([,|]?\d)*$

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

^[1-9][0-9]?(?:[,|][1-9][0-9]?)*$

Explanation:

^            # Start of string
[1-9][0-9]?  # Match a number between 1 and 99
(?:          # Start of optional capturing group:
 [,|]        #  Match one separator
 [1-9][0-9]? #  and a number 1-99
)*           # any number of times (including 0)
$            # End of string

Test it live on regex101.com.

Upvotes: 4

Related Questions