从路径中提取部分字符串 - Java 正则表达式
Extract part of a string from a path - 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 - part1
/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+)/.*", "");
System.out.println(path);
这会打印:
part126
这里的策略是匹配整个URL路径,使用正则表达式捕获组part\d+
保留要提取的组件。
如果您的实际问题是如何隔离 third(左起)路径组件,则只需使用 String#split
:
String input = "/com/testproj/part126/dfb/rgf/string.html";
String path = input.split("/")[3];
System.out.println(path);
我正在尝试提取“/”和“.”之间的字符串的路径。例如,我有一个像“/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 - part1
/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+)/.*", "");
System.out.println(path);
这会打印:
part126
这里的策略是匹配整个URL路径,使用正则表达式捕获组part\d+
保留要提取的组件。
如果您的实际问题是如何隔离 third(左起)路径组件,则只需使用 String#split
:
String input = "/com/testproj/part126/dfb/rgf/string.html";
String path = input.split("/")[3];
System.out.println(path);