Java 字符串 newline/indentation 匹配

Java String newline/indentation matching

我有这个示例字符串(带有 newlines/indentations,标记为“”): 加密货币、水果和方向条目的数量可能会有所不同,但 format/syntax 保持不变。

注意: 我还没有想出如何在问题中添加 space/indentation 所以如果有人知道怎么做,请把说明发给我。谢谢!

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  

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

我打算做一个字符串替换,将 fruit 子字符串替换为什么都没有 ""。 可以使用 indexOf("apple banana") 找到起始索引,但是 endIndex 有点棘手,因为我们在最后一个 "apple banana" 之后有多个 "exit"。

我们之后的出口是最后一个 "apple banana" 入口之后的第一个非缩进出口。最后一个 "apple banana" 条目可以用 lastIndexOf("apple banana") 找到,但是我们如何匹配最后一个 "apple banana" 的第一个非缩进出口?

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

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

  • 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