4

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!

3 Answers 3

7

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
4

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.

Comments

0

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.

1 Comment

The literal dot is inside the range of "any char", so the match will happen, BTW your suggest of [+|-]? will also match "r" : "|725.00", because characters inside brackets(sequence) doesnt need the "OR" operator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.