从路径中提取字符串的部分 – Java正则表达式

huangapple go评论67阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2020年9月22日 13:43:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64003687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定