我有以下字符串:
mmSuggestDeliver(0,新数组("名称","类别","关键字","偏见", "扩展"," ID"),新阵列(新阵列(" Advance Auto Parts Inc.", " Aktien"," 982516 | US00751Y1064 | AAP ||"," 85","", " Advance_Auto_Parts | 982516 | 1 | 13715"),新数组(" iShares China Large Cap UCITS ETF", " Anzeige",""," 100",""," http://suggest-suche-A0DK6Z") ),2,0;)
我想提取以粗体显示的安全性名称。
这是我尝试的:
var regEx = new RegExp(/"\w+\|/, 'g');
var text = 'mmSuggestDeliver(0, new Array("Name", "Category", "Keywords", "Bias", "Extension", "IDs"), new Array(new Array("Britvic Plc", "Aktien", "A0HMX9|GB00B0N8QD54|||", "85", "", "Britvic|A0HMX9|1|15568"),new Array("<div class=\"pull-left mright-5 image_logo_ishares2\"></div><div class=\"pull-left\">iShares MSCI AC Far East ex-Japan UCITS ETF</div>", "Anzeige", "", "100", "", "http://g.finanzen.net/ishares-suggest-suche-A0HGV9")), 2, 0);';
var securityName = regEx.exec(text);
console.log(securityName);
&#13;
仅返回第一个匹配A0HMX9|
。我想要第二个。我怎样才能做到这一点?
谢谢!
答案 0 :(得分:1)
const regex = /"\w+\|/g;
const str = `mmSuggestDeliver(0, new Array("Name", "Category", "Keywords", "Bias", "Extension", "IDs"), new Array(new Array("Advance Auto Parts Inc.", "Aktien", "982516|US00751Y1064|AAP||", "85", "", "Advance_Auto_Parts|982516|1|13715"),new Array("iShares China Large Cap UCITS ETF", "Anzeige", "", "100", "", "http://suggest-suche-A0DK6Z")), 2, 0);`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
&#13;
答案 1 :(得分:1)
正如WiktorStribiżew建议in comments,您可能需要start()
而不是String.prototype.match
:
RegExp.prototype.exec
var regEx = new RegExp(/"\w+\|/, 'g');
var text = 'mmSuggestDeliver(0, new Array("Name", "Category", "Keywords", "Bias", "Extension", "IDs"), new Array(new Array("Britvic Plc", "Aktien", "A0HMX9|GB00B0N8QD54|||", "85", "", "Britvic|A0HMX9|1|15568"),new Array("<div class=\"pull-left mright-5 image_logo_ishares2\"></div><div class=\"pull-left\">iShares MSCI AC Far East ex-Japan UCITS ETF</div>", "Anzeige", "", "100", "", "http://g.finanzen.net/ishares-suggest-suche-A0HGV9")), 2, 0);';
var securityName = text.match(regEx);
console.log(securityName);
会在每次执行时返回一个匹配(请参阅Nata Zakharchuk's answer),而RegExp.prototype.exec
会返回所有匹配项(假设您设置了String.prototype.match
修饰符)。