WestCoastProjects
WestCoastProjects

Reputation: 63172

Assistance on simple regex pattern

What is the correct regex for extracting the resultCount given the following pattern (note I don't care about anything else in the string):

{
 "resultCount":12,
 "results": [blah blah..

Here is the regex I tried.. but no dice (i.e no match..) ..

.*resultCount":([\d]+),.*

Language is java; and this DOES matter (turns out the regex expression works fine in vanilla regex). So i'm going to see if some character like quote is the problem

Upvotes: 1

Views: 60

Answers (1)

Martin Ender
Martin Ender

Reputation: 44279

I suppose you are using the String.matches function in Java which requires the entire string to be matched by the pattern (which is why you included .* before and after the pattern). As Bergi correctly spotted, the . will generally not match the line breaks, so you cannot get a full-string match without using DOTALL.

But that is really a bit of a hack. You are not actually interested in matching the whole string (that is something you do for validation). And Java provides a second method of pattern matching, which takes a bit more code, but allows you to do the job properly (finding substring matches - and multiple of them if needed). Here is some quick sample code with a fixed pattern (assuming str is your input string):

Pattern pattern = Pattern.compile("resultCount\":\\s*(\\d+)");

Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Both Pattern and Matcher are part of java.util.regex. Code based on this tutorial page.

Working demo.

Of course the inclusion of \\s* in the pattern is up to you, but it's definitely something that could happen if you don't generate the JSON yourself, and it can't do any harm, since there's no overlap with \\d.

Upvotes: 1

Related Questions