My requirement is to allow only numbers,.
,<
,-
and <
in certain columns on my datagridview.The example inputs are 2.5
,1-15.5
,>10
,>12.54
,<75
etc
I'm using regex to check the pattern matching following is my code
If System.Text.RegularExpressions.Regex.IsMatch(val, "^[\d.-]+$") Then
Return True
Else
Return False
End If
But this accepts only numbers,.
and -
that means which return true if I pass val="2.5"
or val="5-10"
So my question is how to make it for other symbols(>
,<
)
To make a structural check and be space relaxed you may use something like this:
^(\s*(?:[-><])?\s*\d+(?:[.]\d+)?)+$
Try the regex demo.
This accept also: 1.5 - 10.3
or < 10
but refuse invalid < 10.2.
or 1 - ..
accepted before.
Update
To accept only single number disequality (accept < 10.2
but refuse >10 <5
) and accept at max 2
operands in subtractions (accept 1.2 - 3.4
but refuse 1 -1 - 1
) (as stated by @SebastianProske):
^(\s*[><]\s*\d+([.]\d+)?|\d+([.]\d+)?\s*(-?\s*\d+([.]\d+)?\s*)?)$
PS: to be more precise we can replace all the \s
with [ \t]
to not accept newlines and other whitespace chars.