正则表达式将第一个从“/token1/token2/token3”中分离出来

问题描述

我对正则表达式很不熟悉,但我需要提取以下字符串的第一个标记

输入:/token1/token2/token3

所需输出/token1

我试过了:

List<String> connectorPath = Splitter.on("^[/\\w+]+")
                    .trimResults()
                    .splitToList(actionPath);

对我不起作用,有什么想法吗?

解决方法

可以匹配而不是拆分

^/\\w+

或者如果字符串有 3 个部分,则对第一部分使用捕获组。

^(/\\w+)/\\w+/\\w+$

Java 示例

Pattern pattern = Pattern.compile("^/\\w+");
Matcher matcher = pattern.matcher("/token1/token2/token3");

if (matcher.find()) {
    System.out.println(matcher.group(0));
}

输出

/token1
,

您可以使用 / 正则表达式在不在字符串开头的 (?!^)/ 上拆分:

String[] res = "/token1/token2/token3".split("(?!^)/");
System.out.println(res[0]); // => /token1

参见 Java code demoregex demo

  • (?!^) - 匹配不在字符串开头的位置的负前瞻
  • / - 一个 / 字符。

使用番石榴:

Splitter splitter = Splitter.onPattern("(?!^)/").trimResults();
Iterable<String> iterable = splitter.split(actionPath);
String first = Iterables.getFirst(iterable,"");
,

你把它复杂化了。

试试下面的正则表达式:^(\/\w+)(.+)$

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PathSplitter {
   public static void main(String args[]) {
      String input = "/token1/token2/token3";
      Pattern pattern = Pattern.compile("^(\\/\\w+)(.+)$");
      Matcher matcher = pattern.matcher(input);
      if (matcher.find()) {
         System.out.println(matcher.group(1)); //  /token1
         System.out.println(matcher.group(2)); //  /token2/token3
      } else {
         System.out.println("NO MATCH");
      }
   }
}