2017-03-06 41 views
0

比方說,我有一個字符串s = "xxx -I hello yyy,我想提取給出hello提取一個字符串的子串,給定之前的子串(標誌?)

E.g.我想提出一個功能,說findToken那就是:

function findToken(msg, flag, regexp) { 
    return msg.match(new RegExp(flag + '\\s' + regexp, 'g')); 
} 

,然後當我打電話findToken("xxx -I hello yyy", "-I", "\\w+");我現在得到:

["-I hello"],不過,我想獲得公正['hello'],即。無視國旗。我將如何使用RegExp完成此操作?

+1

使用捕捉集團,並獲得其價值。 –

+0

見https://jsfiddle.net/qapoob25/ –

回答

1

您可以翻轉使用EXEC,添加捕獲組,並在新的數組中返回第一個捕捉:

function findToken(msg, flag, regexp) { 
 
    return [new RegExp(flag + '\\s(' + regexp + ')', 'g').exec(msg)[1]]; 
 
} 
 

 
var result = findToken("xxx -I hello yyy", "-I", "\\w+"); 
 
console.log(result);

0

function findToken(msg, flag, regexp) { 
 
var match=msg.match(new RegExp(flag + '\\s' + regexp, 'g')); 
 
    return match[0].replace(flag+' ',''); 
 
} 
 
console.log(findToken("xxx -I hello yyy", "-I", "\\w+"));

相關問題