我有一个字符串,可以说:
“编号为 1 的学生约翰很聪明。”
我想提取该字符串的可变部分:学生的姓名和号码。
“编号为 1 的学生约翰很聪明。”
“编号为 2 的学生艾伦很聪明。”
我应该如何创建正则表达式?我知道 \\d
提取数字,但是如何提取字符串?
但对于“**H2k Gaming**(第 1 到 **5** 击杀)”
其中变量字符串为“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));
}
关于java - 使用 java 模式和匹配器从字符串中提取变量字符串和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34954221/