在Java中提取某些子字符串

在Java中提取某些子字符串,java,regex,Java,Regex,我有一句话,就是: User update personal account ID from P150567 to A250356. 我想从这个句子中提取关键字“P10567” 如何使用正则表达式或字符串方法提取句子之间的数据? 字符串方法: 使用以下各项的StringUtils.substringBetween(): 正则表达式方法: 使用regexfrom(.*)to,括号中的字符串为 名为组(1),只需将其解压缩: public static void main(String[] ar

我有一句话,就是:

User update personal account ID from P150567 to A250356.
我想从这个句子中提取关键字“
P10567

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

  • 字符串方法:

    使用以下各项的
    StringUtils.substringBetween()

  • 正则表达式方法:

    使用regex
    from(.*)to
    ,括号中的字符串为 名为
    组(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));
    }
    

提示:从索引“from”到索引“to”获取子字符串
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));
}