有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java字符串换行符/缩进匹配

我有这个示例字符串(带有换行符/缩进,标记为“”): 加密货币、水果和方向条目的数量可能不同,但格式/语法保持不变

注: 我还不知道如何在问题中添加空格/缩进,因此如果有人知道如何添加空格/缩进,请将说明发送给我。谢谢

bitcoin litecoin 11  
exit  
bitcoin litecoin 16  
""ripple 77  
""exit    
exit    
**apple banana 55  
exit  
apple banana 55/2  
""coconut 1  
""exit  
""dragonfruit 2  
""exit    
exit**       
north west 11  
exit    
south west 7  
""north 12  
""exit    
exit  

目标是过滤掉所有与水果相关的文本及其相应的退出(用粗体标记)

我计划用字符串替换水果子字符串,而不使用任何“”。 开始索引可以通过indexOf(“applebana”)找到,但是结束索引有点复杂,因为在最后一个“applebana”之后有多个“exit”

我们追求的出口是最后一次“苹果香蕉”进入后的第一个非缩进出口。最后一个“苹果香蕉”条目可以通过lastIndexOf(“苹果香蕉”)找到,但我们如何匹配最后一个“苹果香蕉”的第一个非缩进出口

欢迎任何有效的解决方案!谢谢


共 (1) 个答案

  1. # 1 楼答案

    假设要替换输入中的文本,则:

    • apple banana开头,并且
    • [newline]exit结尾
    • 在这两个术语之间有任何东西吗
    • 其中嵌套的exit语句具有缩进的特性(即通过""

    。。。您可以使用以下基于正则表达式的解决方案:

    // original text
    String text = "bitcoin litecoin 11\nexit\nbitcoin litecoin 16\n\"\"ripple 77\n\"\"exit\nexit\napple banana 55\nexit"
        + "\napple banana 55/2\n\"\"coconut 1\n\"\"exit\n\"\"dragonfruit 2\n\"\"exit\nexit\nnorth west 11\nexit"
        + "\nsouth west 7\n\"\"north 12\n\"\"exit\nexit";
    //                           | starting with fruit
    //                           |            | anything in the middle
    //                           |            |  | ends with newline + exit, then
    //                           |            |  |     | newline or end of input
    //                           |            |  |     |        | dot also represents 
    //                           |            |  |     |        | newlines
    Pattern p = Pattern.compile("apple banana.*?\nexit(\n|$)", Pattern.DOTALL);
    StringBuffer replacement = new StringBuffer();
    Matcher m = p.matcher(text);
    // iteratively replacing with empty
    while (m.find()) {
        m.appendReplacement(replacement, "");
    }
    // appending tail text after last find
    m.appendTail(replacement);
    System.out.println(replacement);
    

    输出

    bitcoin litecoin 11
    exit
    bitcoin litecoin 16
    ""ripple 77
    ""exit
    exit
    north west 11
    exit
    south west 7
    ""north 12
    ""exit
    exit