-5

I am trying to extract a string from a json object using regexs in java.

The string looks like this:

{"key":"value"}

The regex method code looks like this:

public String extractVal(String dataRaw) {
    Pattern p = Pattern.compile(":\"(.+\b)");
    Matcher m = p.matcher(dataRaw); //dataRaw is string from above^
    if (m.matches()) {
        return m.group(1);
    }
    return null;
}

It always just returns null. What did I do wrong?
Thanks in advance

nmagerko
  • 5,616
  • 9
  • 38
  • 71
Plays2
  • 931
  • 4
  • 10
  • 19

2 Answers2

3

There are two issues with your code

  1. \b should be \\b

  2. You should be using find() rather than matches(). The first will do a search on a given string and stops when it finds substring that matches the regex. Second will do a search on entire string. Because the provided regex doesn't match with the full string, the matches() does not work.

Simply fix your code on these two points, then it'll work. Tested myself.

Harry Cho
  • 1,532
  • 2
  • 15
  • 23
0

Found answer using text2re.com

public String extractVal(String dataRaw) {
    String re1=".*?";   // Non-greedy match on filler
    String re2="(?:[a-z][a-z]+)";   // Uninteresting: word
    String re3=".*?";   // Non-greedy match on filler
    String re4="((?:[a-z][a-z]+))"; // Word 1
    Pattern patt = Pattern.compile(re1+re2+re3+re4,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher matc = patt.matcher(dataRaw);
    if (matc.find()) {
        return matc.group(1);
    }
    return null;
}

Still unsure what i screwed up, though.

EDIT: better solution:

public String extractVal(String dataRaw) {
    String test = ".+:\"(.+)\"";
    Pattern patt = Pattern.compile(test,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher matc = patt.matcher(dataRaw);
    if (matc.find()) {
        return matc.group(1);
    }
    return null;
}
Plays2
  • 931
  • 4
  • 10
  • 19