英文:
Extract part of a string from a path - Java Regex
问题
Sure, here are the translated parts:
我试图从路径中提取在斜杠(/)和句点(.)之间的字符串。例如,我有一个路径像 "/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
英文:
I'm trying to extract a string between '/' and '.' of a path. For example, I have a path like "/com/testproj/part1/string.html". I need to extract "part1" from the this path, the "/com/testproject/" is always fixed. I have other paths like /com/testproj/part2/string.html, /com/testproj/part3/string.html.
-
e.g.
-
/com/testproj/part1/dfb/rgf/string.html - part1
-
/com/testproj/part126/dfb/rgf/string.html - part126
-
/com/testproj/part45/dfb/rgf/string.html - part45
答案1
得分: 3
你可以在这里使用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);
英文:
You may use String#replaceAll
here:
String input = "/com/testproj/part126/dfb/rgf/string.html";
String path = input.replaceAll(".*/(part\\d+)/.*", "$1");
System.out.println(path);
This prints:
part126
The strategy here is to match the entire URL path, using a regex capture group part\\d+
to retain the component you want to extract.
If instead your actual question is how to isolate the third (from the left) path component, then just use String#split
:
String input = "/com/testproj/part126/dfb/rgf/string.html";
String path = input.split("/")[3];
System.out.println(path);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论