Search code examples
javaregexguava

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


I'm pretty rusty with regex, but I have the requirement to extract the first token of the following string:

Input: /token1/token2/token3

Required output: /token1

I have tried:

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

Doesn't work for me, any ideas?


Solution

  • You can split on the / that is not at the string start using the (?!^)/ regex:

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

    See the Java code demo and the regex demo.

    • (?!^) - a negative lookahead that matches a location not at the start of string
    • / - a / char.

    Using Guava:

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