使用 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."
我想提取这个字符串的可变部分:学生的姓名和他的编号。
"The student John with the number 1 is smart."
"The student Alan with the number 2 is smart."
我应该如何创建正则表达式?我知道 \d
提取数字,但如何提取字符串?
but for the "**H2k Gaming** (1st to **5** Kills)"
其中变量字符串为"H2k Gaming",变量编号为5
String sentence = "H2k Gaming (1st to 5 Kills)";
String pattern = "[\w ]+ \(1st to (\d+) Kills\)";
它打印:
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));
}
如果字符串始终具有相同的格式,您可以简单地按 " "
拆分并访问正确的索引:
String[] tokens = text.split(" ");
String name = tokens[2];
int number = Integer.parseInt(tokens[6]);
只要形式不变,填空即可。
^The student (.*) with the number (.*) is smart\.$
我有一个字符串,假设:
"The student John with the number 1 is smart."
我想提取这个字符串的可变部分:学生的姓名和他的编号。
"The student John with the number 1 is smart."
"The student Alan with the number 2 is smart."
我应该如何创建正则表达式?我知道 \d
提取数字,但如何提取字符串?
but for the "**H2k Gaming** (1st to **5** Kills)"
其中变量字符串为"H2k Gaming",变量编号为5
String sentence = "H2k Gaming (1st to 5 Kills)"; String pattern = "[\w ]+ \(1st to (\d+) Kills\)";
它打印:
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));
}
如果字符串始终具有相同的格式,您可以简单地按 " "
拆分并访问正确的索引:
String[] tokens = text.split(" ");
String name = tokens[2];
int number = Integer.parseInt(tokens[6]);
只要形式不变,填空即可。
^The student (.*) with the number (.*) is smart\.$