动态正则表达式匹配

时间:2018-06-25 17:55:28

标签: javascript regex

我有一些类似于以下内容的字符串:

var resource1 = '/myapi/person/pascal/address/town';
var resource2 = '/myapi/person/john/address/town';
var resource3 = '/myapi/person/messi/address/town';

这是我到目前为止尝试过的:

模式是:

var pattern = '/myapi/person/(.*)/address/town';

这是我到目前为止尝试过的:

var resource1 = '/myapi/person/pascal/address/town';
var resource2 = '/myapi/person/john/address/town';
var resource3 = '/myapi/person/messi/address/town';
var pattern = '/myapi/person/(.*)/address/town';

var pattern = new RegExp(pattern);
if (pattern.test(resource1)){
    console.log('yes');   
}

问题

如何动态使用该模式检查resource1resource2resource3是否与pattern相匹配?

致谢。

2 个答案:

答案 0 :(得分:0)

以下正则表达式应该起作用:

/\/myapi\/person\/(.*)\/address\/town/

它可以像这样使用:

var string = '/myapi/person/pascal/address/town';
var re = /\/myapi\/person\/(.*)\/address\/town/;
re.test(string); //will return true

我鼓励您在这里看看它是如何工作的: https://regexr.com/3ri4m

答案 1 :(得分:0)

我建议使用更严格的模式。使用否定的字符类而不是贪婪的通配符。

let resources = ['/myapi/person/pascal/address/town',
                 '/myapi/person/john/address/town',
                 '/myapi/person/messi/address/town'];

var regex = new RegExp('/myapi/person/([^/]+)/address/town');
for (var i = 0, len = resources.length; i < len; i++) {
  if(regex.test(resources[i]))
    console.log(`valid: ${resources[i]}`);   
}

您已在人员姓名变量周围放置了一个捕获组。如果您打算捕获那些,则可以使用.exec代替.test:

let resources = ['/myapi/person/pascal/address/town',
                 '/myapi/person/john/address/town',
                 '/myapi/person/messi/address/town'];

var regex = new RegExp('/myapi/person/([^/]+)/address/town');
for (var i = 0, len = resources.length; i < len; i++) {
  if ((m = regex.exec(resources[i])) !== null) {
          console.log(m[1]);
  }
}