正则表达式中有效格式的问题

时间:2021-03-04 09:56:13

标签: javascript regex regexp-replace

我正在使用正则表达式模式匹配添加对字符串的限制,但它不起作用,因为我在正则表达式方面没有太多经验。 就像不可能没有(没有)或[没有]。

abc.(%      -->false
abc.)%      -->false
abc.(%]     -->false
abc.)%]     -->false
1abc9.(%[   -->false
abc.)%[     -->false
abc.(%(     -->false
abc.)%)     -->false
19.(%)%     -->true
19.[%]%     -->true
2009% --> true
19.1245 -- true 
10.[5-9]% -- true
/^[^\s\[\]^$.|A-Z]*(?:(?:\[[^\s\[\]\\]+](?!\])|%[^\r\n\?\$\*\.\[\+\(\)\]\.\^%]+%(?=\||$)|\|[^\s\[\]^A-Z\\]+)[^\s\[\]^$.|?*+()A-Z\\]*)*$/

The string is fine if it have start with ( and end with )
19[1-3] is fine
2014.56(core) is fine

1 个答案:

答案 0 :(得分:2)

我可能会使用允许的白名单来解决这个问题,而不是试图四处奔波并涵盖所有负面情况。也就是说,使用以下正则表达式模式:

^\S+\.(?:(?:\(%\)|\[%\])%?)?$

Demo

一些JS代码:

var valid = "19.(%)";
if (/^\S+\.(?:(?:\(%\)|\[%\])%?)?$/.test(valid)) {
    console.log("VALID:   " + valid);
}

var invalid = "abc.(%";
if (!/^\S+\.(?:(?:\(%\)|\[%\])%?)?$/.test(invalid)) {
    console.log("INVALID: " + invalid);
}

相关问题