在Java中提取某些子字符串

时间:2018-03-12 02:47:53

标签: java regex

我有一句话,是:

User update personal account ID from P150567 to A250356.

我想提取关键字" P10567"从这句话。

如何使用正则表达式或字符串方法在句子之间提取数据?

1 个答案:

答案 0 :(得分:2)

  • 字符串方法:

    使用Apache CommonsStringUtils.substringBetween()

    public static void main(String[] args) {
        String sentence = "User update personal account ID from P150567 to A250356.";
        String id = StringUtils.substringBetween(sentence, "from ", " to");
        System.out.println(id);
    }
    
  • 正则表达式方法:

    使用正则表达式from (.*) to,括号括起来的字符串是 叫group(1),只需提取它:

    public static void main(String[] args) {
        String regex = "from (.*) to";
        String sentence = "User update personal account ID from P150567 to A250356.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sentence);
        matcher.find();
        System.out.println(matcher.group(1));
    }