正则表达式有很多细节及特殊情况,不同的场景需要根据实际需求进行组合使用
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
public static void main(String[] args) {
String input = "John Smith is a software developer, his phonenumber is 123-456-7890";
String pattern = "(\\w+)\\s(\\w+)\\s.*\\s.*,.*(\\d{3}-\\d{3}-\\d{4})";
// Compile the pattern
Pattern p = Pattern.compile(pattern);
// Get a matcher object
Matcher m = p.matcher(input);
if (m.find()) {
// Get the whole match
System.out.println("Whole match: " + m.group());
// Get the first captured group
System.out.println("First captured group: " + m.group(1));
// Get the second captured group
System.out.println("Second captured