views:

57

answers:

2

Hi all;

Csharp Regex Pattern:

Regex rg = new Regex("(?i)(?<=>)[^<]+(?=</TD>)");

JavaScript Regex Pattern:

var pattern = (?i)(?<=>)[^<]+(?=</TD>);

var result = str.match(pattern);

Csharp Regex pattern work, but javascript regex pattern not work pls help ?

+2  A: 

Assuming you have an HTML fragment in form of a string and are in a browser, trying to consume it with 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
}

See? No regular expressions necessary - the browser has a perfectly capable HTML parser built-in, no need to make your own. When using a JavaScript framework like jQuery, the above gets even easier:

$("<TD>33,7</TD><TD>100</TD><TD>20,0</TD>").find("td").each( function() {
  alert( $(this).text() );
});
Tomalak
A: 

There aren't lookbehinds, or inline modifiers in JavaScript RE. So we move the (?i) to the end of the regexp: //i. The lookbehind is a bit harder to mimic, so its easier to just accept the fact that it can't be done and instead use a capture group to find what you need:

var pattern = />([^<]+)<\/TD>/i;
var result = str.match(pattern);

// the match you want is in result[1]

EDIT: Seems to work fine on both strings you provided:

"<td class='asd'>sd</td>".match(/>([^<]+)<\/TD>/i)
// [">sd</td>", "sd"]

If you want to match multiple items in the same string you can abuse the replace() method something like this:

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"]
gnarf
@gnarf pls <td>bla1</td> work but other 'td' <td class='asd'>sd</td> not work other td
Oraclee
@gnarf pls help
Oraclee
@oraclee: Boy… you sure do have the wrong attitude. How about commenting on the actual solutions you got and answering the questions you have been asked instead of sprinkling "does not work" and "pls help" comments all over the place.
Tomalak