我寫了一個正則表達式來匹配HTML文本和它works in regex101.com。JavaScript RegExp錯誤 - 無法重複
<h2>Dollarkurs\sAktuell<\/h2><\/div><div[^>?]+><div><table>
<colgroup><col[^>?]+><col><col[^>?]+><\/colgroup><tbody><tr>
<td[^>?]+>Kurs<\/td><td[^>?]+>([^\s^<?]+)\s*<span[^>?]+>
(\+|-)?\d+\,?\d{0,2}%<\/span><span[^>?]+><\/span><\/td>
<\/tr><tr><td[^>?]+>Kurszeit<\/td><td[^>?]+>
(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?\sUhr
<\/td><\/tr><tr><td[^>?]+>Kursdatum<\/td><td[^>?]+>([0-9\.]+)<\/td>
測試字符串是:
<h2>Dollarkurs Aktuell</h2></div><div class='content'><div><table>
<colgroup><col width='50px'><col><col width='100px'></colgroup><tbody><tr>
<td class='bold'>Kurs</td><td class='textRight' colspan='2'>1,0947 <span class='distanceLeft right green'>
+0,58%</span><span class='distanceLeft right imageIconPriceGreen'></span></td>
</tr><tr><td class='bold' colspan='2'>Kurszeit</td><td class='textRight'>
16:00:00 Uhr
</td></tr><tr><td class='bold' colspan='2'>Kursdatum</td><td class='textRight'>28.04.2015</td>
但在節目中,我得到這個錯誤:
Uncaught SyntaxError: Invalid regular expression: Nothing to repeat
這裏是我的代碼:
var htmlTxt = "<h2>Dollarkurs Aktuell</h2></div><div class='content'><div><table><colgroup><col width='50px'><col><col width='100px'></colgroup><tbody><tr><td class='bold'>Kurs</td><td class='textRight' colspan='2'>1,0947 <span class='distanceLeft right green'>+0,58%</span><span class='distanceLeft right imageIconPriceGreen'></span></td></tr><tr><td class='bold' colspan='2'>Kurszeit</td><td class='textRight'>16:00:00 Uhr</td></tr><tr><td class='bold' colspan='2'>Kursdatum</td><td class='textRight'>28.04.2015</td>";
var re = new RegExp("<h2>Dollarkurs\sAktuell<\/h2><\/div><div[^>?]+><div><table><colgroup><col[^>?]+><col><col[^>?]+><\/colgroup><tbody><tr><td[^>?]+>Kurs<\/td><td[^>?]+>([^\s^<?]+)\s*<span[^>?]+>(\+|-)?\d+\,?\d{0,2}%<\/span><span[^>?]+><\/span><\/td><\/tr><tr><td[^>?]+>Kurszeit<\/td><td[^>?]+>(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?\sUhr<\/td><\/tr><tr><td[^>?]+>Kursdatum<\/td><td[^>?]+>([0-9\.]+)<\/td>", "gmi");
var result = re.exec(htmlTxt);
while (result != null) {
document.write("["+re.lastIndex+"] "+result);
document.write("<br />");
}
將整個問題帶到這裏。 –
請在這裏發佈您的相關代碼和錯誤消息,並且不要鏈接到其他網站來描述您的問題。 – tjati
[不要用正則表達式解析HTML](http://stackoverflow.com/a/1732454/418066) – Biffen