首页 > 解决方案 > 从路径中提取部分字符串 - Java Regex

问题描述

我正在尝试提取“/”和“。”之间的字符串。的一条路径。例如,我有一个类似“/com/testproj/part1/string.html”的路径。我需要从这个路径中提取“part1”,“/com/testproject/”总是固定的。我还有其他路径,例如 /com/testproj/part2/string.html、/com/testproj/part3/string.html。

标签: javaregexstringextract

解决方案


你可以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);

推荐阅读