简体   繁体   English

Javascript正则表达式:测试文本是否仅包含集合中的字符

[英]Javascript regex: test if text contains only characters from a set

How it is better to check (test) if text contains only characters from set (for example if text contains only punctuation marks) 检查(测试)文本是否仅包含来自集合的字符(例如,如果文本仅包含标点符号)更好

var regex = /[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g

res = text.replace(regex, '')

if (res) return false

so I made it with replace is it possible to do it with regex.test? 所以我用替换它是可以用regex.test做的吗?

Yes it is. 是的。 There are two possibilities. 有两种可能性。 One is, that you use anchors to assert that the full string is made up of these: 一个是,你使用来断言完整的字符串是由这些组成的:

var regex = /^[\.,-\/#!$%\^&\*;:{}=\-_`~()]+$/;
if(regex.test(text))

Alternatively you can use a negated character class and see whether it matches and then again negate the result 或者,您可以使用否定的字符类,看它是否匹配,然后再次否定结果

var regex = /[^\.,-\/#!$%\^&\*;:{}=\-_`~()]/;
if(!regex.test(text))

Note that ,-\\/ is a range that includes ,-./ . 需要注意的是,-\\/是包括范围,-./ This is redundant and may become a source of errors if the character class is ever changed. 这是多余的,如果字符类被更改,可能会成为错误的来源。 You might want to simplify your character class to: 您可能希望将角色类简化为:

[.,\/#!$%^&*;:{}=_`~()-]

(Or the negated version of that, depending on which approach you choose.) (或者否定版本,取决于您选择的方法。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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