我有以下字符串:
"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);
如何同时取消xmin
和xmax
?
答案 0 :(得分:3)
使用non-greedy正则表达式匹配最少的。
var srctext = "The length must be between <xmin> and <xmax> characters";
var re = srctext.match(/<(.*?)>/g);
console.log(re);
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);