Synchrowave
Synchrowave

Reputation: 89

Regex, only match with strings that contain one occurence of certain characters

I have the following regular expression:

^[-]?([+]?[\d]+[-+*/]?)+$

My objective is to match strings that contain arithmetic expressions and integers. Which it is successful in, except one case. When it comes to equals signs. I only want this expression to match strings that contain at most one equals sign. Which would mean that it would match

7=7

but not

7=7=7

since the second string has two occurrences of the equals sign.

I tried using curly braces {} and I think I need something like

={0,1}

which would match with strings that have exactly one or no occurrencces of "=". But I do unfortunately not know how to incorporate it in my regex.

Upvotes: 1

Views: 1119

Answers (2)

Tony B
Tony B

Reputation: 333

If you wish to match strings with only one equals sign then you want to not match strings with no equals and also not match strings with more than one equals. A regex like so:

^(?!.*=.*=)(?![^=]*$)[-+*\/\d=]+$

Unfortunately, this will match strings like 9=. Probably not desired.

I suspect then that you want to both match strings of form a=b and strings of form a, where a and b are arithmetic expressions. This even handles negative numbers:

^-?\d+([-+*\/]-?\d+)*(=-?\d+([-+*\/]-?\d+)*)?$

See live example here: https://regex101.com/r/9vONUT/1

Upvotes: 0

Puschi
Puschi

Reputation: 249

Since you only want to match arithmetic expressions and integers I changed your code to find everything if it has numbers, operators or a equal sign: ^[-+*\/\d=]+$. I needed to escape the character / -> \/

To match only one equal sign I addes a negative lookahead: (?!.*=.*=). If it finds whats insinde the brackets, the whole regex wont match. For example if you have a word mytext : (?!mytext) the whole regex won't match. .* means it finds everything (. stands for every character and the * say's it can be there 0 to unlimited times).

So this is the solution:

^(?!.*=.*=)[-+*\/\d=]+$

See live example here: https://regex101.com/r/zhSEmf/1/

Also your code didn't worked for -4*-4.

Edit: Since you don't want your code to start with / or * I added id in the negative lookahead: ^(?!.*=.*=|[\/*].*)[-+*\/\d=]+$

Upvotes: 2

Related Questions