【问题标题】:How to include a dictionary in this regex expression如何在此正则表达式中包含字典
【发布时间】:2020-05-27 20:52:16
【问题描述】:
我从 Javascript 开始,我创建了这个函数来验证输入时的某些单词,(返回 true 或 false)
export default function validate(props) {
return props.match(/war|gun|kill/g) != null;
}
但是我以后会包含更多的单词并且正则表达式会很长,你能告诉我一个更好的方法来重写这个函数吗?
【问题讨论】:
标签:
javascript
arrays
regex
dictionary
【解决方案1】:
您可以维护一个单词列表,并在单词中包含正则表达式,例如guns? 表示单数和复数形式。
这是基于您的示例的flagString 函数:
function flagString(str) {
const bannedRe = new RegExp('\\b(' + banned.join('|') + ')\\b', 'i');
return bannedRe.test(str);
}
var banned = [ 'guns?', 'kill', 'war' ];
console.log(flagString('this is ok')); // returns false
console.log(flagString('guns are not ok')); // returns true
console.log(flagString('to kill is not ok')); // returns true
注意事项:
-
'\\b(' 和 ')\\b' 将单词锚定在边界上,这是为了避免误报
-
.join('|') 使用 OR 将单词连接成一个正则表达式,以便您可以一次性测试字符串的性能