用于分离路径的正则表达式

7

您好,我正在尝试使用Java正则表达式从以下路径信息中获取所需的上下文路径。

String path = "/Systems/lenovo/";

我想编写正则表达式来分别获取"/Systems"和"/lenovo"。我尝试使用分组的以下正则表达式,但结果并不如预期。
String systemString = path.replaceAll("(.*)(/\\w+)([/][\\w+])", "$2") - to get "/Systems" - not working

String lenovoString = path.replaceAll("(.*)(/\\w+)([/][\\w+])", "$3") - to get "/lenovo" - working.

有人能告诉我我的正则表达式可能出了什么问题吗?


对于这种操作,“Pattern”是一个更为明智的选择。 - SJuan76
5个回答

3
你可以尝试。
String PATH_SEPARATOR = "/"; 
String str = "/Systems/lenovo/";
String[] res = str.substring(1).split(PATH_SEPARATOR);

IDEONE DEMO

如果你想在字符串前面保留/,那么你可以直接添加它:

"/"+res[0]

IDEONE DEMO


2

只需像这样拆分:

String[] parts = path.replaceAll("/$", "").split("(?=/)");
replaceAll() 方法用于移除末尾的斜杠(如果有的话)。
请参见演示
String path = "/Systems/lenovo/";
String[] parts = path.replaceAll("/$", "").split("(?=/)");
Arrays.stream(parts).forEach(System.out::println);

生产
/Systems
/lenovo

巧妙保留 / 的方法! - Stephan

1

不应该使用 replaceAllgroups ($3) 的方法来达到您想要的效果。

使用您的方法,背后发生的事情是:

正则表达式 (.*)(/\\w+)([/][\\w+]) 匹配字符串 /Systems/l

您的表达式被分成以下组:

$1 => (.*)
$2 => (/\\w+)
$3 => ([/][\\w+])

每个组匹配了您匹配字符串的以下部分 /Systems/l
$1 => ''
$2 => /Systems
$3 => /l

当你执行以下代码时:
```java path.replaceAll("(.*)(/\\w+)([/][\\w+])", "$3") ```
实际上是在做以下操作:
'/Systems/lenovo/'.replaceAll(`/Systems/l`, '/l') => '/lenovo'

当您使用$2时。
'/Systems/lenovo/'.replaceAll(`/Systems/l`, '/Systems') => '/Systemsenovo/'

因此,对于这个任务来说使用正则表达式组并不是很合理,最好像其他人在本页面上建议的那样使用简单的String.split方法。

0
你可以尝试这个:
String path = "/Systems/lenovo/";
String[] arr = path.split("/");
String str1 = "/"+arr[1];
String str2 = "/"+arr[2];
System.out.println("str1 = " + str1);
System.out.println("str2 = " + str2);

结果如下:

str1 = /Systems
str2 = /lenovo

0
要获取/Systems,您需要使用此正则表达式:(?:\/[^\/]+), 而对于/lenovo,您需要:(?:\/[^\/]+){1}(?=\/$)
您可以尝试这个(请参见http://ideone.com/dB3edh):
   String path = "/Systems/lenovo/";
    Pattern p = Pattern.compile("(?:\\/[^\\/]+)");
    Matcher m = p.matcher(path);

    if(m.find()) {
        System.out.println(m.group(0));
    }
    p = Pattern.compile("(?:\\/[^\\/]+){1}(?=\\/$)");
    m = p.matcher(path);
    if(m.find()) {
        System.out.println(m.group(0));
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接