views:

92

answers:

3

I am trying to search this string:

,"tt" : "ABC","r" : "+725.00","a" : "55.30",

For:

"r" : "725.00"

And here is my current code:

Pattern p = Pattern.compile("([r]\".:.\"[+|-][0-9]+.[0-9][0-9]\")");
Matcher m = p.matcher(raw_string);

I've been trying multiple variations of the pattern, and a match is never found. A second set of eyes would be great!

+4  A: 

The next line should read:

if ( m.find() ) {

Are you doing that?

A few other issues: You're using . to match the spaces surrounding the colon; if that's always supposed to be whitespace, you should use + (one or more spaces) or \s+ (one or more whitespace characters). On the other hand, the dot between the digits is supposed to match a literal ., so you should escape it: \. Of course, since this is a Java String literal, you need to escape the backslashes: \\s+, \\..

You don't need the square brackets around the r, and if you don't want to match a | in front of the number you should change [+|-] to [+-].

While some of these issues I've mentioned could result in false positives, none of them would prevent it from matching valid input. That's why I suspect you aren't actually applying the regex by calling find(). It's a common mistake.

Alan Moore
A: 

First thing try to escape your dot symbol: ...[0-9]+\.[0-9][0-9]...
because the dot symbol match any character...

Second thing: the [+|-]define a range of characters but it's mandatory...
try [+|-]?

Alban.

Alban Soupper
+2  A: 

Your regexp actually works, it's almost correct

Pattern p = Pattern.compile("\"[r]\".:.\"[+|-][0-9]+.[0-9][0-9]\"");
Matcher m = p.matcher(raw_string);
if (m.find()){
    String res = m.toMatchResult().group(0);
}
Fedor
Matcher ISA MatchResult, so `m.group(0)` (or even `m.group()`) will suffice. +1 for catching the missing quote, and for getting rid of the all-encompassing capturing group.
Alan Moore