1

I would like JavaScript style innerHTML in Java. For instance, I want to get 'TRUE' from the string below:

String control = "<div class='myclass'>TRUE</div>";

But my pattern seems to be off as find() returns false. Ideas anyone?

Pattern pattern = Pattern.compile(">(.*?)<");
Matcher matcher = pattern.matcher(control);

if(matcher.find()) {
    result = matcher.group(1);
}
TheRed__
  • 164
  • 11

2 Answers2

2

get rid of the question mark:

public static void main(String[] args) {
    String control = "<div class='myclass'>TRUE</div>";
    Pattern pattern = Pattern.compile(">(.*)<");
    Matcher matcher = pattern.matcher(control);
    String result = null;
    if(matcher.find()) {
        result = matcher.group(1);
    }
    System.out.print(result);
}

BTW it would be better to learn how to use java's DOM objects and XPath classes.

msknapp
  • 1,595
  • 7
  • 22
  • 39
  • Your BTW is the really the only way of doing it. – Shafiq Jetha Dec 20 '13 at 00:43
  • System.out.print(control.replaceAll("<[^>]*>", "")); – msknapp Dec 20 '13 at 00:46
  • This is exactly what I need. DOM and XPath are too heavyweight. I'm not working with fully formed documents but rather snippets from a WCMS. The expected String 'should' never have nested tags. @Jeff Storey jquery is also out as this process occurs in a pre-rendering state on the server. Thanks everyone. – TheRed__ Dec 20 '13 at 12:58
0

Either use Jquery or if you really insist on doing it in Java, try using JSoup to strip out the HTML and return on the safe stuff

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64