【发布时间】:2015-04-29 03:55:32
【问题描述】:
我有一个包含以下记录的文件:
drwxr-xr-x - root supergroup 0 2015-04-05 05:26 /user/root
drwxr-xr-x - hadoop supergroup 0 2014-11-05 11:56 /user/root/input
drwxr-xr-x - hadoop supergroup 0 2014-11-05 03:06 /user/root/input/foo
drwxr-xr-x - hadoop supergroup 0 2015-04-28 03:06 /user/root/input/foo/bar
drwxr-xr-x - hadoop supergroup 0 2013-11-06 15:54 /user/root/input/foo/bar/20120706
-rw-r--r-- 3 hadoop supergroup 0 2013-11-06 15:54 /user/root/input/foo/bar/20120706/_SUCCESS
drwxr-xr-x - hadoop supergroup 0 2013-11-06 15:54 /user/root/input/foo/bar/20120706/_logs
drwxr-xr-x - hadoop supergroup 0 2013-11-06 15:54 /user/root/input/foo/bar/20120706/_logs/history
在 Java 代码中,我使用 Pattern 和 Matcher 类来获取稍后要处理的子字符串。代码如清单所示:
String filename = "D:\\temp\\files_in_hadoop_temp.txt";
Pattern thePattern
= Pattern.compile("[a-z\\-]+\\s+(\\-|[0-9]) (root|hadoop)\\s+supergroup\\s+([0-9]+) ([0-9\\-]+) ([0-9:]+) (\\D+)\\/?.*");
try
{
Files.lines(Paths.get(filename))
.map(line -> thePattern.matcher(line))
.collect(Collectors.toList())
.forEach(theMather -> {
if (theMather.find())
{
System.out.println(theMather.group(3) + "-" + theMather.group(4) + "-" + theMather.group(6));
}
});
} catch (IOException e)
{
e.printStackTrace();
}
结果如下:
0-2015-04-05-/user/root
0-2014-11-05-/user/root/input
0-2014-11-05-/user/root/input/foo
0-2015-04-28-/user/root/input/foo/bar
0-2013-11-06-/user/root/input/foo/bar/
0-2013-11-06-/user/root/input/foo/bar/
0-2013-11-06-/user/root/input/foo/bar/
0-2013-11-06-/user/root/input/foo/bar/
但我的预期结果是前三行没有尾部“/”。我尝试了许多模式来去除拖尾“/”但失败了。
您能否提供一些关于去除尾部“/”的模式的建议。
非常感谢。
【问题讨论】:
-
正则表达式将仅匹配现有字符串。前 3 个字符串不以“/”结尾。因此,只需使用 if 条件,如果不存在则添加结尾 '/'。