使用 java 模式和匹配器从字符串中提取可变字符串和数字

Extract a variable string and a number from a string using java patterns and matcher

我有一个字符串,假设: "The student John with the number 1 is smart."

我想提取这个字符串的可变部分:学生的姓名和他的编号。

我应该如何创建正则表达式?我知道 \d 提取数字,但如何提取字符串?

它打印:

Name: Gaming
Number: 5
String sentence = "The student John with the number 1 is smart.";
String pattern = "The student (\w+) with the number (\d+) is smart.";

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(sentence);

if(m.find()) {
    System.out.println("Name: " + m.group(1));
    System.out.println("Number: " + m.group(2));
}

See it in action

如果字符串始终具有相同的格式,您可以简单地按 " " 拆分并访问正确的索引:

String[] tokens = text.split(" ");
String name = tokens[2];
int number = Integer.parseInt(tokens[6]);

只要形式不变,填空即可。

^The student (.*) with the number (.*) is smart\.$