-2

I have the string "SELECTOR('(namespace=''ar.com.osde.reintegros'' and eventname=''generacionReintegro'')')".

I need return the string that is between "SELECTOR(" and ")", the result should be: '(namespace=''ar.com.osde.reintegros'' and eventname=''generacionReintegro'')'.

My code with the regular expression is:

public static String extractSelector(String txt){
    Pattern pattern = Pattern.compile("^SELECTOR\\((.*)\\)$");
    Matcher m = pattern.matcher(txt);
    String s = null;
    while (m.find()) {
        s = m.group(1);
    }
    return s;
}

Where txt = "SELECTOR('(namespace=''ar.com.osde.reintegros'' and eventname=''generacionReintegro'')')"

But this always return null. Why is that?

Erwin Bolwidt
  • 28,093
  • 15
  • 46
  • 70

1 Answers1

-1

This jdoodle demonstrates that that part of the code works (only added a declaration for txt and removed the return statement). Are you sure there is nothing done with the txt before that?

Given your code, the only explanation is that txt does not match the pattern fully... This because the while-loop is not executed at all (thus find is always false).

Perhaps there are spaces between SELECTOR and the opening bracket (, perhaps SELECTOR can be put in lowercase. In order to debug this, you can perhaps write

System.out.println("\""+txt+"\"");

Before actually matching it, or use the debugger features of your IDE to do this. The quotes are used to make the spaces more explicit.

Willem Van Onsem
  • 321,217
  • 26
  • 295
  • 405
  • 1
    This is a comment, not an answer. – Brandon Buck Jan 22 '15 at 18:26
  • @BrandonBuck: updated it with advice on how to debug. Since it provides ways to fully diagnose the problem, this is more than a comment... – Willem Van Onsem Jan 22 '15 at 18:27
  • If it doesn't provide a means to resolve the problem (debugging isn't an answer, it's a recommendation) it's still not an answer. – Brandon Buck Jan 22 '15 at 18:29
  • @BrandonBuck: It does, the only possible reason why this doesn't work is because the while loop isn't executed. That's the only possible explanation because if `txt` was not effective, it would give a `NullPointerException`. The objective of SO is not to resolve problems. It is to share knowledge Q/A-like. That's one of the things people don't tend to pick up. – Willem Van Onsem Jan 22 '15 at 18:35