簡體   English   中英

用於選擇介於('和'

[英]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(''

這個詞之后。 例如,我想檢索“ Bacon ,“ Paprika或“ Sliced 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()函數來僅獲取每次出現的$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. 最后一個括號還是一個特殊字符,需要轉義。 您無需使用此括號,因為顯然可以將其停在'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM