Reputation: 1
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
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
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