Csharp的正则表达式:JavaScript的正则表达式问题
Regex rg = new Regex("(?i)(?<=>)[^<]+(?=</TD>)");
JavaScript的正则表达式:
var pattern = (?i)(?<=>)[^<]+(?=</TD>);
var result = str.match(pattern);
Csharp的正则表达式模式的工作原理,但JavaScript的正则表达式模式行不通请帮助?
Csharp的正则表达式:JavaScript的正则表达式问题
Regex rg = new Regex("(?i)(?<=>)[^<]+(?=</TD>)");
JavaScript的正则表达式:
var pattern = (?i)(?<=>)[^<]+(?=</TD>);
var result = str.match(pattern);
Csharp的正则表达式模式的工作原理,但JavaScript的正则表达式模式行不通请帮助?
假设你在一个字符串形式有一个HTML片段,并在浏览器中,试图用JavaScript来使用它:
var str = "<TD>33,7</TD><TD>100</TD><TD>20,0</TD>";
var temp = document.createElement("tr");
temp.innerHTML = str;
var tds = temp.getElementsByTagName("td")
for (var i=0; i<tds.length; i++) {
alert(tds[i].textContent); // use .innerText in Internet Explorer
}
看到了吗?没有必要的正则表达式 - 浏览器内置了一个功能完善的HTML解析器,不需要自己创建。当使用像jQuery JavaScript框架,上面变得更简单:
$("<TD>33,7</TD><TD>100</TD><TD>20,0</TD>").find("td").each(function() {
alert($(this).text());
});
有没有lookbehinds,或在JavaScript RE内联改性剂。所以我们将(?i)
移动到正则表达式的末尾://i
。在回顾后是有点难以模仿,所以它更容易只接受一个事实,即它不能做,而是使用捕捉组来找到你所需要的:
var pattern = />([^<]+)<\/TD>/i;
var result = str.match(pattern);
// the match you want is in result[1]
编辑:看起来工作精细您提供两个字符串:
"<td class='asd'>sd</td>".match(/>([^<]+)<\/TD>/i)
// [">sd</td>", "sd"]
如果你想匹配相同的字符串多个项目可以
AB
使用replace()
方法是这样的:
var textInTds = []; // empty array we will fill up:
"<td>bla1</td><td class='asd'>sd</td>".replace(/>([^<]+)<\/TD>/ig, function($0, $1) {
textInTds.push($1); // push onto the array
return $0; // return the original text so that it doesn't destroy the string
});
// textInTds -> ["bla1", "sd"]
请输入bla1工作但其他'td'sd不能工作其他td – Chicharito 2010-05-12 14:11:02
@oraclee:男孩......你肯定有错误的态度。如何评论你得到的实际解决方案,并回答你被问到的问题,而不是“不起作用”和“请帮助”的评论。 – Tomalak 2010-05-12 15:17:41
您应该接受以前问题的答案。 – Alsciende 2010-05-12 13:21:49
您正试图使用正则表达式解析HTML。请不要这样做,这是错误的,危险的,完全没有必要的。 – Tomalak 2010-05-12 13:25:27
@Alsciende请帮助你的代码不起作用 – Chicharito 2010-05-12 13:40:46