【问题标题】:Javascript Unicode Redex matching NOT a letter or a numberJavascript Unicode Redex 不匹配字母或数字
【发布时间】:2020-12-01 01:57:19
【问题描述】:

我想转换这个:

var result = mystring.replace(/[^a-zA-Z0-9]+/g, ' ');

到一个正常运行的 unicode 版本,这样我就可以只索引字母和数字。例如,我不想要 [-_%...]。由于 JS 本身不支持这个,所以我使用的是xregexp

这似乎没有给我任何结果...我这里的字母和数字部分正确吗?

<script src="https://unpkg.com/xregexp/xregexp-all.js"></script>
<script>
    var s = `joanthan------______++++++ <me> bornss $%^&\` asdfasdf+++áeé´sé´s , н, п, р, с, т, ф, х, ц, ч`;
    var r1 = XRegExp.replace(s, /[^\p{L}\p{N}]+/g, ' ');
    var r2 = s.replace(/[^a-zA-Z0-9]+/g, ' ');
    console.log(r1);
    console.log(r2);
</script>

想法?谢谢!

【问题讨论】:

  • 你的扩展正则表达式不应该用引号括起来吗?
  • 不,没关系,我仍然没有得到不同的结果 '/[^\p{L}\p{N}]+/g' 不需要引号,因为您可以看到常规正则表达式工作正常。

标签: javascript regex replace unicode xregexp


【解决方案1】:

为了将 Unicode 属性转义与 RegExp(以及扩展名 XRegExp)一起使用,您需要设置 Unicode 标志。

const s = `joanthan------______++++++ <me> bornss $%^&\` asdfasdf+++áeé´sé´s , н, п, р, с, т, ф, х, ц, ч`;
let r1 = s.replace(/[^\p{L}\p{N}]+/gu, ' ')
console.log(r1);

【讨论】:

  • 虽然另一个答案在技术上是我所要求的,但这要好得多,因为我不需要导入任何东西。谢谢!
【解决方案2】:

根据他们的documentationreplace支持两个匹配参数; stringRegexp。话虽如此,它不会解析字符串表达式,因此将被视为文字字符串替换。要使用xregex,您首先必须创建一个表达式实例,然后将其用作参数。

var s = `joanthan------______++++++ <me> bornss $%^&\` asdfasdf+++áeé´sé´s , н, п, р, с, т, ф, х, ц, ч`;
var match = XRegExp('[^\\p{L}\\p{N}]+', 'g');
var r1 = XRegExp.replace(s, match, ' ');
var r2 = s.replace(/[^a-zA-Z0-9]+/g, ' ');

console.log(r1);
console.log(r2);
&lt;script src="https://unpkg.com/xregexp/xregexp-all.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2011-09-12
    • 2016-09-03
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2019-08-21
    • 1970-01-01
    相关资源
    最近更新 更多