Split Brain
Split Brain

Reputation: 1

Regular expression to validate a string representing either number or addition of numbers

Help on validation expression to validate a string representing either number or addition of numbers.

e.g:

2 OK
22 + 3 OK
2+3 not OK
2 +3 not OK
2 + 34 + 45 OK
2 + 33 + not OK
2 + 33+ 4 not OK

Upvotes: 0

Views: 813

Answers (2)

stema
stema

Reputation: 92986

This would be quite a simple pattern

^\d+(?: \+ \d+)*$

See it here on Regexr

^ anchor for the start of the string

$ anchor for the end of the string

The anchors are needed, otherwise the pattern will match "partly"

\d+ is at least one digit

(?: \+ \d+)* is a non capturing group that can be there 0 or more times (because of the * quantifier at the end)

Upvotes: 4

a'r
a'r

Reputation: 36999

Try:

/^\d+(\s+\+\s+\d+)*$/

This matches a number followed by an optional plus sign and number, which can then be repeated.

Upvotes: 1

Related Questions