regex - Extract two numbers from a String with the Java Matcher class -
regex - Extract two numbers from a String with the Java Matcher class -
i'ld extract 2 numbers string looks like: "views: 120 upvotes: 540". expected result 120 , 540. i'ld java matcher class. how can accomplish this, in other words what's pattern that's required accomplish this?
to utilize matcher start compiling pattern, phone call matcher(string) , see if matches. finally, can parse values. like,
string str = "views: 120 upvotes: 540"; pattern p = pattern.compile("views:\\s*(\\d+)\\s+upvotes:\\s*(\\d+)", pattern.case_insensitive); matcher m = p.matcher(str); if (m.matches()) { int views = integer.parseint(m.group(1)); int upvotes = integer.parseint(m.group(2)); system.out.printf("%d %d%n", views, upvotes); } output is
120 540
java regex
Comments
Post a Comment