简体   繁体   中英

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.

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=]+$

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 numbers. Then this will work:

^[-+*\/\d]+(=[-+*\/\d]+){0,1}$

Unfortunately, this will match strings like *9=+8 but fixing this would make the regex much more complex and thus less suitable as an example. For example this for an expression without an equals: Regular Expression for Simple Arithmetic String

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM