【问题标题】:Regex for selecting beween (' and '用于在 (' 和 ' 之间进行选择的正则表达式
【发布时间】:2017-06-01 21:44:42
【问题描述】:

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

这是我的代码:

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

我怎样才能做到正确?

【问题讨论】:

  • 先使用jsdom提取onclick属性。 (或以下段落)

标签: javascript regex string match regex-negation


【解决方案1】:

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

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

这是一个运行示例。您需要使用.exec() 函数仅获取每个出现的$1 组。

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 字符串)包围
  2. 您需要使用斜线对( 进行转义,因为括号是正则表达式组的开头。
  3. 您为什么要寻找其中没有} 的集合?您可以查找任何字符 (.)。
  4. 如果您在没有? 的情况下使用*,它将是贪婪的,并且只会在文档中最后一次出现时停止。通常,您希望选择器不要贪心。
  5. 最后一个括号又是一个特殊字符,需要转义。你不需要这个括号,因为它显然已经足够停在'

【讨论】:

  • 你太棒了!太感谢了!找了将近一个星期,你很快就解决了!也非常感谢您的解释,因为它有很大帮助!
猜你喜欢
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
相关资源
最近更新 更多