简体   繁体   中英

Regex to include certain characters and two words (true and false)

I want to use eval() in JavaScript to evaluate equations and logical expressions. To sanitize the input, I only want to allow numbers, math operators and the words 'true' and 'false'.

The first part I got down: /^[\\d\\+\\-\\*\\/()\\|&!<>=]+$/ matches digits and operators.

I found out that adding true and false to the brackets will match any accumulation of those letters. Various other permutations of regex commands have at times validated any string containing 'true' or even any string containing any of the characters allowed.

All I want is to include true and false to list of acceptable characters, so to speak.

I'm using JavaScript with the match() method.

You can use the OR operator and a non-capture group to keep the order of the letters in true and false , and using word boundaries to prevent other word characters getting around them:

/^(?:[\d+*\/()|&!<>=-]|\btrue\b|\bfalse\b)+$/i

I removed some of the escapes in your regex since many metacharacters in regex become literal characters in a character class, except - , which I put at the end when removing the backslash.

I also added the case-insensitive flag so that you can match both uppercase characters for true and false too.

You might also want to accept spaces in there, but since I don't really know what your inputs could be, I didn't add it myself.

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