java - Regular Expressions example -
i’m bit confused example... don’t understand written in string pattern. also, find? learning tutorialspoint.
please, can me understand it?
code:
import java.util.regex.matcher; import java.util.regex.pattern; public class regexmatches { public static void main(string args[]) { // string scanned find pattern. string line = "this order placed qt3000! ok?"; string pattern = "(.*)(\\d+)(.*)"; // create pattern object pattern r = pattern.compile(pattern); // create matcher object. matcher m = r.matcher(line); if (m.find()) { system.out.println("found value: " + m.group(0)); system.out.println("found value: " + m.group(1)); system.out.println("found value: " + m.group(2)); } else { system.out.println("no match"); } } } output:
found value: order placed qt3000! ok?
found value: order placed qt300
found value: 0
the pattern has 3 capture groups
(.*)means 0 or more of character (capture group 1)(\\d+)means 1 or more digits (capture group 2)(.*)means 0 or more of character (capture group 3)
when find() called "attempts find next subsequence of input sequence matches pattern." (matcher.find())
when call these lines:
system.out.println("found value: " + m.group(0)); system.out.println("found value: " + m.group(1)); system.out.println("found value: " + m.group(2)); m.group(0)means entire string regex evaluatedm.group(1)refers capture group 1 (zero or more of character)m.group(2)refers capture group 2 (one or more digits)- you're not outputting capture group 3 (zero or more of character)
you'll see m.group(1) returned this order placed qt300 , last 0 left behind m.group(2) because capture group 2 must have @ least 1 digit.
if add capture group 3 (m.group(3)) output display remaining string after last 0 of m.group(2).
in other words:
system.out.println("found value: " + m.group(0)); system.out.println("found value: " + m.group(1)); system.out.println("found value: " + m.group(2)); system.out.println("found value: " + m.group(3)); would display:
found value: order placed qt3000! ok? found value: order placed qt300 found value: 0 found value: ! ok? hope helps!
Comments
Post a Comment