【问题标题】:Extract part of a string from a path - Java Regex [closed]从路径中提取部分字符串 - Java Regex [关闭]
【发布时间】:2020-09-22 05:43:00
【问题描述】:

我正在尝试提取 '/' 和 '.' 之间的字符串的一条路径。例如,我有一个类似“/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

【问题讨论】:

  • 你说你想提取'/'和'.'之间的字符串。的路径,对于"/com/testproj/part1/string.html" 将是part1/string,但你说你只想要part1。是哪个?
  • @Bohemian 请找到一些路径示例.. /com/testproj/part1/dfb/rgf/string.html, /com/testproj/part2/dfb/rgf/string.html, /com /testproj/part3/dfb/rgf/string.html, /com/testproj/part4/dfb/rgf/string.html, /com/testproj/part14545/dfb/rgf/string.html .. 对于每个路径我需要提取路径及其编号..
  • 您要搜索的文本是否总是文字 part 后跟一些数字?
  • 来自/com/testproj/part4/dfb/rgf/string.html 你需要part4 还是part4/dfg/rgf
  • 从您的示例中,仅第 4 部分,添加了一些有问题的示例..

标签: java regex string extract


【解决方案1】:

您可以在这里使用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);

【讨论】:

  • 谢谢蒂姆。我正在使用正则表达式寻找答案。
  • @user3222372 我的回答使用正则表达式。查看String#split 的源代码以亲自查看。
  • 以上 expr 不适用于此示例 - "/com/test-proj/part1/abc/xyz/string.html"
  • 您的问题暗示(在我看来强烈)您想要提取 last 路径组件。如果您在上面的输入是有效的,那么您还需要向我们提供如何知道path1 可能在哪里的逻辑。
  • 在路径中,“/com/testproj/”始终是固定的。之后,我有部分后面跟着一个数字。在“part”之后,我可以拥有任何级别的子文件夹..
猜你喜欢
  • 2014-08-23
  • 2011-06-26
  • 2021-09-20
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
  • 2014-06-24
  • 2013-03-02
  • 1970-01-01
相关资源
最近更新 更多