0

I have sample string as below :

input - {"page":1,"per_page":10,"total":76,"total_pages":8,"data":""}

I want to filter out the total_pages as 8 in a sample Java program. For that I thought to build a regex to filter out substring as "total_pages":8,

Below is code .

**String regex = "/(.*total_pages.*?,/)";
String res =  "{\"(page\":1,\"per_page\":10,\"total\":76,\"total_pages\":8,\"data\":)";
System.out.println(res);
System.out.println(Pattern.matches(regex,res));**

Please tell why It never matches with the substring.

Booboo
  • 38,656
  • 3
  • 37
  • 60
Rishi
  • 43
  • 5
  • I also tried using other regex as : "(.*total_pages.*?,)" , ".*total_pages.*?," , ".*total_pages.*" but nothing get matched . – Rishi Mar 18 '20 at 10:57
  • Use `Matcher.find()` with `String regex= "\"total_pages\":(\\d+)"` and then use `if (m.find()) { System.out.println(matcher.group(1)); }` , see the [code example here](https://stackoverflow.com/questions/237061/using-regular-expressions-to-extract-a-value-in-java) – Wiktor Stribiżew Mar 18 '20 at 12:16
  • It works fine using Matcher but I am unable to understand why Pattern.matches() does not retrun true if any parts getting matched. Is Pattern.matches() looks for complete string to be matched with the pattern ? – Rishi Mar 18 '20 at 15:12
  • See https://stackoverflow.com/questions/8923398/regex-doesnt-work-in-string-matches – Wiktor Stribiżew Mar 18 '20 at 15:20

0 Answers0