我正在使用 https://www.npmjs.com/package/bad-words我创建了用于过滤特殊字符的正则表达式。
const Filter = require('bad-words');
const badWordsFilter = new Filter({replaceRegex: /[A-Za-z0-9öÖÇ窺ĞğİıÜü_]/g});
badWordsFilter.addWords(['badword', 'şğ'])
如果单词不包含土耳其语字符,它就可以工作。但如果我写土耳其语字符,如 ş 或 ğ,它就不是过滤。
我的正则表达式错了吗?
我在文档中找到这段代码:
var filter = new Filter({ regex: /\*|\.|$/gi });
var filter = new Filter({ replaceRegex: /[A-Za-z0-9가-힣_]/g });
//multilingual support for word filtering
最佳答案
您显然遇到了编码问题,因为您的正则表达式无法在您的应用程序中运行,请参见此处:https://regex101.com/r/VpItfH/3/ .
所以我认为在您的应用程序的正则表达式中对您的字符进行编码可能会有所帮助:
在此处查看编码的正则表达式结果:https://regex101.com/r/VpItfH/4/
更多详情
在 PCRE 正则表达式引擎中尝试以下编码的正则表达式将起作用(https://regex101.com/r/VpItfH/5):
/[A-Za-z0-9\x{f6}\x{d6}\x{c7}\x{e7}\x{15e}\x{15f}\x{11e}\x{11f}\x{130}\x{131}\x{dc}\x{fc}_]/g
but when selecting a javascript regex engine the {
,}
will break the unicode so you need to remove them and if the character is not recognized then replace \x
与 \u0
。例如。 \x{15e}
变成 \u015e
然后你可以像使用 /[A-Za-z0-9öÖÇ窺ĞğİıÜü_]/g
一样进行匹配。
Note: to get the unicode form of a character, you can do
"Ğ".charCodeAt(0).toString(16);
and prefix it with\x
or\u0
.
希望这可以有所帮助,并且至少承认您可以在正则表达式中对字符进行编码并且仍然匹配相同的内容。 :)
关于javascript - 带有特殊字符的坏词过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733681/