将正则表达式字符串转换为包含unicode字符类转义的正则表达式对象

问题描述 投票:0回答:1

我有一个包含正则表达式的数据对象

data = {regex : "/^[\p{L} .’_-]+$/u"}

在 js 文件中,我使用此模式来匹配字符串

var s = "check";
var pattern = new RegExp(data.regex);
console.log(pattern.test(s));

上面的代码不起作用。模式变为 //^[p{L} .’_-]+$/u/ 并导致 false,并且额外的斜杠也附加到正则表达式。

如何解决这个问题,结果可能是这样的 pattern = /^[\p{L} .’_-]+$/u 但在正则表达式对象中?

javascript regex object unicode-escapes
1个回答
0
投票

要包含 Unicode 字符类转义,应在模式外部添加“u”标志。

这是修复后的代码:

let data = {regex : "^[\p{L} .’_-]+$"}

// You should separate your regex string from flags.
let split = data.regex.split('/');
let pattern = new RegExp(split[1], 'u'); // Specifying unicode flag "u" separately.

let s = "check";
console.log(pattern.test(s));
© www.soinside.com 2019 - 2024. All rights reserved.