我有一个字符串,让我们说:
"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
答案 0 :(得分:2)
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));
}
答案 1 :(得分:1)
如果字符串始终具有相同的格式,您可以简单地按" "
拆分并访问正确的索引:
String[] tokens = text.split(" ");
String name = tokens[2];
int number = Integer.parseInt(tokens[6]);
答案 2 :(得分:0)
只要形式不变,就得到空白。
^The student (.*) with the number (.*) is smart\.$