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

标签 java regex matcher

我有一个字符串,可以说: “编号为 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));
}

See it in action

关于java - 使用 java 模式和匹配器从字符串中提取变量字符串和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34954221/

相关文章:

java - Spring Boot 和 Junit 的 Maven 依赖

java.lang.NoClassDefFoundError : org/apache/commons/discovery/tools/DiscoverSingleton

c# - 正则表达式 包含在 XML 元素中

javascript - 返回匹配的先行组

使用反射和匹配器的Java方法

java - 匹配器在匹配后抛出 IllegalStateException

java - Matcher.find() 如何工作

java - apache tiles 与自定义 tagx ("fragment")

regex - Python重新转义正则表达式模式中的巧合括号

java网络启动时间