字符串中的所有字符必须与正则表达式匹配 [英] All characters in a string must match regex
问题描述
对不起,如果以前没有解决过,但是我在Google上找不到能满足我需求的任何东西.
I'm sorry if this has been up before but I can't find anythin on google that gives what I want.
我在一个字段中可以编写表达式:x>1
,x>2||x<1
(x>1) && (x<2)
等.
我想要的是一个用于检查表达式的正则表达式,因此它只能包含某些有效字符以防止代码注入. a.1
应该不匹配.
I've a field where you can write expressions: x>1
, x>2||x<1
(x>1) && (x<2)
etc.
What I want is a regex that checks the expression so it only can contain a certain valid characters to defend against code injection. a.1
should not match.
到目前为止,我正在使用它:
So far I'm using this:
expression.match('[xX<>=|0-9&().]')
但是这还会返回包含这些字符中任何一个的任何内容.我想要的是一个仅在所有字符都与正则表达式中的任何thoose匹配时返回的表达式.
But this also returns anything that contains any of these characters. What I want is a expression that only returns if all character match any of thoose in the regex.
推荐答案
在字符类和锚点之后,您需要*
或+
量词:
You need *
or +
quantifier after your character class and anchors:
/^[xX<>=|0-9&()\s.]*$/.test(expression)
^ ^^
现在,它将匹配
-
^
-字符串的开头 -
[xX<>=|0-9&\s().]*
-零个或多个(如果使用+
,则为一个或多个)在char类中定义的字符 -
$
-字符串结尾.
^
- start of string[xX<>=|0-9&\s().]*
- zero or more (if you use+
, one or more) of the chars defined in the char class$
- end of string.
简短演示:
console.log(/^[xX<>=|0-9&\s().]*$/.test("a.1"));
console.log(/^[xX<>=|0-9&\s().]*$/.test("(x>1) && (x<2)"));
请注意,我也添加了\s
来匹配空格.
Note I added \s
to match whitespaces, too.
这篇关于字符串中的所有字符必须与正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!