简体   繁体   中英

Regular Expression to accept only 0,1,(,),|,&

I am trying to create a regular expression that contains only below 6 characters in a string

0,1,(,),|,&

I came up with this regular expression

^[0-1\\|()\\&]$

But it seems to fail even when valid string is given as input. As below

const inputStr = "(0&(1&(1|0))";
const validateStr = new RegExp("^[0-1\|\(\)\&]$");
const isValid = validateStr.test(inputStr);

Above need to be returned true, but the output of isValid is false. Please let me know where I am doing wrong.

You need to add a plus after your character set to search the whole string!

 const inputStr = "(0&(1&(1|0))"; const validateStr = new RegExp(/^[0-1()|&]+$/); const isValid = validateStr.test(inputStr); console.log(isValid); 

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