正则表达式从“/token1/token2/token3”中拆分第一个

Regex to split the first from a "/token1/token2/token3"

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

输入:/token1/token2/token3

所需输出:/token1

我试过:

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

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

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

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

参见Java code demo and the regex 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");
      }
   }
}

您可以匹配

而不是拆分
^/\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