java - 从路径中提取部分字符串 - Java Regex
问题描述
我正在尝试提取“/”和“。”之间的字符串。的一条路径。例如,我有一个类似“/com/testproj/part1/string.html”的路径。我需要从这个路径中提取“part1”,“/com/testproject/”总是固定的。我还有其他路径,例如 /com/testproj/part2/string.html、/com/testproj/part3/string.html。
例如
/com/testproj/part1/dfb/rgf/string.html - 第 1 部分
/com/testproj/part126/dfb/rgf/string.html-part126
/com/testproj/part45/dfb/rgf/string.html - part45
解决方案
你可以String#replaceAll
在这里使用:
String input = "/com/testproj/part126/dfb/rgf/string.html";
String path = input.replaceAll(".*/(part\\d+)/.*", "$1");
System.out.println(path);
这打印:
part126
这里的策略是匹配整个 URL 路径,使用正则表达式捕获组part\\d+
来保留要提取的组件。
相反,如果您的实际问题是如何隔离第三个(左起)路径组件,则只需使用String#split
:
String input = "/com/testproj/part126/dfb/rgf/string.html";
String path = input.split("/")[3];
System.out.println(path);
推荐阅读
- node.js - 如何将 JPG 上传到 AWS Lambda (NodeJS)
- python - 将 python 2 转换为 python 3:读取图像文件
- java - 如何让我的变量的输出从最小到最大排序?
- algorithm - 确定凹点
- swift - 如何创建一个从两个不同数组的值返回匹配项的函数?
- android - Android:有没有办法将 ItemTouchHelper.SimpleCallback 对象附加到单个 CardView?
- javascript - 提示框 - 当前日期格式
- excel - 在办公室 JS 加载项中,我如何删除不确定是否存在的工作表?
- c# - 如何在宏的坐标上保持检查颜色?
- python - 如何在不使用 elif 的情况下增加值?