I'm trying to come up with a set of regex checks to validate a string that should be a valid mathematical expression.
I'm limiting the expression to include:
The 4 standard operators: +, -, *, /
Curly brackets: ( and )
Integers and decimals.
So I'm not allowing any functions like min, max, sin, tan, etc.
So far I have:
Regex can be a bit opaque to me so I'm more interested in making it readable/understandable rather then concatenating everything into a single regex pattern.
Can anyone spot anything I'm missing or that I've got wrong?
Thanks.
Edit: changed the CalcRegexCheckOK sub because I got very confused between Regex.IsMatch and Regex.Matcher
I'm limiting the expression to include:
The 4 standard operators: +, -, *, /
Curly brackets: ( and )
Integers and decimals.
So I'm not allowing any functions like min, max, sin, tan, etc.
So far I have:
Validate mathematical expression with regex:
Private Sub CalcRegexCheckOK (s As String) As Boolean
Dim lst As List = Array As String( _
$"[^\d()\*\/\+\-\.]"$, _ 'basic allowed characters (negated match with ^)
$"\A[\/\*\)\.]"$, _ 'not allowed at start of string
$"[\+\-\/\*\(\.]\z"$, _ 'not allowed at end of string
$"(\-|\*|\/|\+|\(|\)|\.)\1"$, _ 'duplicate individual characters
$"[\+\-\*\/\.]{2,}"$, _ 'invalid consecutive characters
$"[\+\-\*\/\.\(]\)"$, _ '+ - * / . ( can't go directly befe )
$"[\.\)]\("$, _ '. and ) can't go directly before (
$"\d+\.\d+\.\d+"$) 'nonsense 'double' decimals like 112.23.34
For Each pattern As String In lst
Dim m As Matcher = Regex.Matcher(pattern, s)
If m.Find Then Return False
Next
Return True
End Sub
Regex can be a bit opaque to me so I'm more interested in making it readable/understandable rather then concatenating everything into a single regex pattern.
Can anyone spot anything I'm missing or that I've got wrong?
Thanks.
Edit: changed the CalcRegexCheckOK sub because I got very confused between Regex.IsMatch and Regex.Matcher
Last edited: