获取2个字符之间的所有字符串

时间:2017-01-04 13:56:07

标签: jquery regex

我有以下字符串:

"The length must be between <xmin> and <xmax> characters"

我正在尝试获取<>之间的所有单词/字符串但是使用我的代码我只得到以下内容:

xmin> and <xmax

这是我的代码:

var srctext = "The length must be between <xmin> and <xmax> characters";
    var re = srctext.match(/\<(.*)\>/).pop();
    console.log(re);

如何同时取消xminxmax

1 个答案:

答案 0 :(得分:3)

使用non-greedy正则表达式匹配最少的。

var srctext = "The length must be between <xmin> and <xmax> characters";
var re = srctext.match(/<(.*?)>/g);
console.log(re);

或使用negated character class

var srctext = "The length must be between <xmin> and <xmax> characters";
var re = srctext.match(/<([^>]*)>/g);
console.log(re);

更新:要在正则表达式包含g(全局)标记时获取捕获的值,请使用带有while循环的RegExp#exec方法。

var srctext = "The length must be between <xmin> and <xmax> characters",
    regex=/<([^>]*)>/g,
    m,res=[];

while(m=regex.exec(srctext))
  res.push(m[1])
  
console.log(res);