繁体   English   中英

我想念什么? 试图让正则表达式工作来自json

[英]What am I missing? Trying to get Regex to work that came from json

我有这个正则表达式都在我的json文件中转义了。

"\/^Grocer(?:ies|y)[ \\t]*(\\S+)?\/gmi"

然后,我尝试将其放入新的正则表达式中

  var re = new RegExp("\/^Grocer(?:ies|y)[ \\t]*(\\S+)?\/gmi");
  console.log(re.exec("Groceries"));

但是失败了。 所以我想也许是逃脱了,所以我使用了unescape()给了我。

  var re = new RegExp("/^Grocer(?:ies|y)[ \t]*(\S+)?/gmi");
  console.log(re.exec("Groceries"));

仍然失败。

我认为您正在寻找:

var re = new RegExp("^Grocer(?:ies|y)[ \t]*(\S+)?", "gmi");
console.log(re.exec("Groceries"));

输出: ["Groceries", ...]

开头和结尾的/也被转义( \\/ ),并且您包括了那些。 它们也需要删除。

尝试这个:

var s = "\/^Grocer(?:ies|y)[ \\t]*(\\S+)?\/gmi";
var parts = s.match(/\/(.*)\/(\w*)/);
var re = new RegExp(parts[1], parts[2]);
console.log(re.exec("Groceries"));

JS中的Regex通常不需要在字符串两边加上引号,因此请尝试

 var re = new RegExp(/^Grocer(?:ies|y)[ \t]*(\S+)?/gmi);
 console.log(re.exec("Groceries"));

在此处可以找到更多信息: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

如果要遍历JSON对象,则可能需要对循环的每次迭代执行类似的操作

// while you are in the loop
var thisRegex = unescape( thisLoopItem ); // fill this in with the current item

// locate the final slash
var finalSlash = thisRegex.lastIndexOf('/');

// use substr to return the string before and after the slash to
// populate both parts of the RegExp function
var re = new RegExp( thisRegex.substr( 0, finalSlash ), thisRegex.substr( finalSlash + 1 ) );
console.log(re.exec("Groceries"));

可能需要进行一些调整,但是按照这些原则进行工作即可。

RegExp构造函数签名如下

var re = new RegExp(pattern[, flags])

例如: new RegExp('abc', 'i');

因此,以下代码将为您工作。

var regTxt ="\/^Grocer(?:ies|y)[ \\t]*(\\S+)?\/gmi" // from Json
var regexParts = regTxt.match(/\/(.*)\/(\w*)/)
var re = new RegExp(regexParts[1], regexParts[2]);
console.log(re.exec("Groceries"));

输出: ["Groceries", ..]

暂无
暂无

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

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