我有一条路dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext
我想一次处理一个片段。对于每个段,我想知道它前面有多少个选项卡,并且我希望路径的其余部分保持完整。对于给定的示例
迭代 1:
Preceding tabs: 0
Segment: dir
Rest: \n\tsubdir1\n\tsubdir2\n\t\tfile.ext
迭代 2:
Preceding tabs: 1
Segment: subdir1
Rest: \n\tsubdir2\n\t\tfile.ext
迭代 3:
Preceding tabs: 1
Segment: subdir2
Rest: \n\t\tfile.ext
迭代 4:
Preceding tabs: 2
Segment: file.ext
Rest: ""
我想出的模式是 ((?<=\\R)\\h*)(\\H+)
。然而,这给了我 \tsubdir1\n
作为第一场比赛。我做错了什么?
最佳答案
由于所有部分均由行分隔符 \n
分隔您可以简单地使用.+
匹配它们,因为默认情况下点 .
无法匹配行分隔符,因此您确定它会在 \n
之前停止(或任何其他行分隔符,如 \r
)。
您还可以添加一些组来将选项卡与实际段分开,例如 named group (?<tabs>\t*)
在每场比赛开始时匹配零个或多个选项卡。
要在匹配后打印其余文本,只需在最后一个匹配字符的索引之后的子字符串(您可以通过 Matcher#end
获取它)。
打印包含 \n
的字符串和\t
(不是作为文字,而是作为一对反斜杠和字母)您可以手动替换每个 "\n"
与 "\\n"
和"\t"
与 "\\t"
或使用实用程序类,如 StringEscapeUtils
来自org.apache.commons.lang
其中包含 escapeJava
为我们做这件事的方法。
所以你的代码可以是这样的:
String path = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext";
Pattern p = Pattern.compile("(?<tabs>\t*)(?<segment>.+)");//dot can't match line separators
Matcher m = p.matcher(path);
int i = 1;
while(m.find()){
System.out.println("iteration: " + i++);
System.out.println("Preceding tabs: " + (m.group("tabs").length()));
System.out.println("Segment: " + m.group("segment"));
System.out.println("Rest: "+ StringEscapeUtils.escapeJava(path.substring(m.end())));
System.out.println();
}
输出:
iteration: 1
Preceding tabs: 0
Segment: dir
Rest: \n\tsubdir1\n\tsubdir2\n\t\tfile.ext
iteration: 2
Preceding tabs: 1
Segment: subdir1
Rest: \n\tsubdir2\n\t\tfile.ext
iteration: 3
Preceding tabs: 1
Segment: subdir2
Rest: \n\t\tfile.ext
iteration: 4
Preceding tabs: 2
Segment: file.ext
Rest:
关于java - 使用制表符和换行符解析路径的正则表达式模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55055788/