要求:
從給定的字串("{[Mary:12],[Tom:20],[Jhon:32]}"
)中提取姓名和相應的年齡
程式碼:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by StrayCat on 2018/9/4.
*/
public class Test {
public static void main(String[] args) {
String info = "{[Mary:12],[Tom:20],[Jhon:32]}";
Pattern compile = Pattern.compile("\\[(\\w+?)\\:(\\d{1,3})\\],?");
Matcher matcher = compile.matcher(info);
while (matcher.find()) {
System.out.println("Name:" + matcher.group(1) + "\t Age:" +matcher.group(2));
}
}
}
複製程式碼