【问题标题】:Extract certain substring in Java在Java中提取某些子字符串
【发布时间】:2018-08-20 00:23:01
【问题描述】:

我有一句话,就是:

User update personal account ID from P150567 to A250356.

我想从这句话中提取关键字“P10567”。

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

【问题讨论】:

  • 提示:从“from”索引到“to”索引获取子字符串

标签: java regex


【解决方案1】:
  • 字符串方法:

    使用StringUtils.substringBetween() 中的Apache Commons

    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));
    }
    

【讨论】:

    【解决方案2】:

    考虑这个字符串:

          String s = “Hey Hello from Scaler”
    

    如果您只想要程序输出中的“Hello”子字符串,则调用 substring 方法,将 4 作为其 startIndex,9 作为其 endIndex,因为您希望给定字符串的部分从索引 0 开始并以索引结束8.

    String s_substring = s.substring(4, 9)
    //s_substring will contain “Hello” which is substring of string s
    

    在此处阅读有关Using Substring Method in Java 的更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 2019-03-06
      • 1970-01-01
      • 2020-12-27
      • 2023-01-10
      • 2022-11-13
      • 1970-01-01
      相关资源
      最近更新 更多