2017-01-04 71 views
2
所有字符串

我有以下字符串:獲得2個字符之間

"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

回答

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);


UPDATE:要當正則表達式包含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);

+1

哦,等等。你是對的。 –

相關問題