Reputation: 199
I'm going to need a regular expression that only allows numbers, spaces, decimal numbers with precision of 2, and & sign.
This regular expression will be used to check for an input that allows multiple numbers separated by & sign, and there can be space (optional, but maximum one) in between. The following is what I've tried, due to my poor understanding in regex, they worked so poorly.
^(?=.*[0-9])[ &.0-9]+$
but it doesn't work well.
because things like &&&&&&1 will pass the check.
have also tried things like this, which also works so poorly
^([0-9]{1,}[.]{0,1}[0-9]{0,2}[ ]{0,1}+[&]{0,1}[ ]{0,1})*?$
The following exemplifies what I expected
12 ---> (pass)
12.12 ---> (pass)
12 & 129.12 & 11 --- >(pass)
12 & 129. & 11 ---> (should not pass)
12 & .129 ---> (should not pass)
12 & 129..1 (should not pass)
12 & 129.111 (should not pass)
&&&1 (should not pass)
.......
Many thanks in advance
Upvotes: 3
Views: 1100
Reputation: 163632
To account for the spaces, you might make them optional using ?
You might use a repeating pattern matching 2 optional spaces and an ampersand:
^\d+(?:\.\d{2})?(?: ?& ?\d+(?:\.\d{2})?)*$
Explanation
^
Start of string\d+(?:\.\d{2})?
Match 1+ digits and optionally match a dot and 2 digits(?:
Non capturing groupo
[ ]?&[ ]?
Match an optional space (used [ ]
for clarity), &
and optional spaced+(?:\.\d{2})?
Match 1+ digits and optionally match a dot and 2 digits)*
Close non capturing group and repeat 0+ times to also allow a single entry$
End of stringUpvotes: 1