这个正则表达式应该在任何字符串中找到任何一位、两位或三位数字(如果他们是 102 岁):
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestClass {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d\\d?\\d?");
Matcher m = p.matcher("some string with a number like this 536 in it");
while(m.find()){
System.out.println(m.group()); //This will print the age in your string
System.out.println(m.start()); //This will print the position in the string where it starts
}
}
}
或者这个来测试整个字符串:
Pattern p = Pattern.compile("I, am awesome. And I'm \\d{1,3} years old"); //I've stolen Michael's \\d{1,3} bit here, 'cos it rocks.
Matcher m = p.matcher("I, am awesome. And I'm 65 years old");
while(m.find()){
System.out.println(m.group());
System.out.println(m.start());
}