【问题标题】:Java substring using lastindexOf return a specific length使用 lastindexOf 的 Java 子字符串返回特定长度
【发布时间】:2018-09-25 16:16:32
【问题描述】:

我正在使用 JAVA,我有一个名为 example 的字符串,看起来像;

example = " id":"abcd1234-efghi5678""tag":"abc" "

注意:我没有使用 \ 逃脱“的”,但你明白了..

...我只想回来;

abcd1234

...我一直在尝试使用子字符串

example = (example.substring(example.lastIndexOf("id\":\"")+5));

(因为这个字符串可能在 HTML/JSON 文件中的任何位置)lastIndexOf 所做的所有工作就是找到它,然后保留它之后的所有内容 - 即它返回;

abcd1234-efghi5678""标签":"abc"

基本上我需要根据字符串找到 lastIndexOf 并限制它之后返回 - 我发现我可以执行另一个类似这样的子字符串命令;

example = (example.substring(example.lastIndexOf("id\":\"")+5));
example = example.substring(0,8);

...但它看起来很乱。有什么方法可以使用 lastIndexOf 并同时设置最大长度 - 这可能是一件非常简单的事情,由于长时间盯着它看,我看不到。

非常感谢您的帮助!

【问题讨论】:

    标签: java string substring lastindexof


    【解决方案1】:

    不要substring 两次。改为使用找到的索引两次:

    int idx = example.lastIndexOf("id\":\"");
    example = example.substring(idx + 5, idx + 13);
    

    或者,如果长度是动态的,但总是以 - 结尾:

    int start = example.lastIndexOf("id\":\"");
    int end = example.indexOf('-', start);
    example = example.substring(start + 5, end);
    

    在实际代码中,您当然应该始终检查是否找到了子字符串,即 idx / start / end 不是 -1

    【讨论】:

    • 是的,这行得通——我喜欢如何在后面的子字符串命令中使用开始和结束的标签——谢谢!
    【解决方案2】:

    您可以使用正则表达式来查找特定的子字符串:

    String regex = "^id[^a-z0-9]+([a-zA-Z0-9]+)-.*$";
    Matcher p = Pattern.compile(regex).matcher(example);
    
    String result = null;
    if (p.matches()) {
        result = p.group(1);
    }
    
    System.out.println(result); //outputs exactly "abcd1234"
    

    该模式使用与id 后跟非字母数字字符和前面- 匹配的捕获组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 2023-04-01
      • 2023-02-25
      • 1970-01-01
      相关资源
      最近更新 更多