用于在 (' 和 ' 之间进行选择的正则表达式

Regex for selecting beween (' and '

我试图寻找答案,但没有适合我需要的答案...

这是我的代码:

<div><svg onclick="addIngredient('Bacon', -1);"><path></path></svg>
<button onclick="addIngredient('Bacon', 1);"></button><p>6 Bacon</p></div>

<div><svg onclick="addIngredient('Paprika', -1);"><path></path></svg>
<button onclick="addIngredient('Paprika', 1);"></button><p>3 Paprika</p></div>

<div><svg onclick="addIngredient('Sliced Meat', -1);"><path></path></svg>
<button onclick="addIngredient('Sliced Meat', 1);"></button><p>1 Sliced Meat</p></div>

我想捕捉之间的话语 svg onclick="addIngredient(''

词后。例如,我想检索单词 BaconPaprikaSliced Meat

我试过这样做,但没用..

var stringy = '<div><svg onclick="addIngredient('Bacon', -1);"><path></path></svg>
<button onclick="addIngredient('Bacon', 1);"></button><p>6 Bacon</p></div>

<div><svg onclick="addIngredient('Paprika', -1);"><path></path></svg>
<button onclick="addIngredient('Paprika', 1);"></button><p>3 Paprika</p></div>

<div><svg onclick="addIngredient('Sliced Meat', -1);"><path></path></svg>
<button onclick="addIngredient('Sliced Meat', 1);"></button><p>1 Sliced Meat</p></div>';

var result = stringy.match("svg onclick="addIngredient(([^}]*)')");
console.log(result);

我怎样才能做对?

您可以使用以下正则表达式。它使用 .*? 匹配尽可能少的字符,直到出现下一个 '

<svg.+?onclick="addIngredient\('(.*?)'

这是一个 运行 示例。您需要使用 .exec() 函数来仅获取每次出现的 </code> 组。</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre><code>var stringy = document.getElementById("main").innerHTML; // read the HTML instead of hard-coding it here as a string var regex = /<svg.+?onclick="addIngredient\('(.*?)'/g; var match = regex.exec(stringy); while(match !== null) { console.log(match[1]); match = regex.exec(stringy); }

<div id="main">
    <div><svg onclick="addIngredient('Bacon', -1);"><path></path></svg>
    <button onclick="addIngredient('Bacon', 1);"></button><p>6 Bacon</p></div>

    <div><svg onclick="addIngredient('Paprika', -1);"><path></path></svg>
    <button onclick="addIngredient('Paprika', 1);"></button><p>3 Paprika</p></div>

    <div><svg onclick="addIngredient('Sliced Meat', -1);"><path></path></svg>
    <button onclick="addIngredient('Sliced Meat', 1);"></button><p>1 Sliced Meat</p></div>
</div>


只是为了提高你的正则表达式技能对你的错误的解释:

var regex = "svg onclick="addIngredient(([^}]*)')";
                         ^             ^   ^ ^  ^
  1. 您需要使用 \ 转义 ",因为您的整个正则表达式都被 " (JavaScript strings)
  2. 包围
  3. 您需要用斜杠转义 (,因为方括号是正则表达式组的开头。
  4. 你为什么要找一个没有 } 的集合?您可以只查找任何字符 (.).
  5. 如果您使用的是 * 而没有 ?,它将是贪婪的并且只会在文档中的最后一次出现时停止。通常,您希望选择器不要贪心。
  6. 最后一个括号又是一个特殊字符,需要转义。你不需要这个括号,因为它显然已经足够停在 '.