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

Viewed 89

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?

3 Answers

Instead of split, you can match

^/\\w+

Or if the string has 3 parts, use a capture group for the first part.

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

Java example

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

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

Output

/token1

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

You are over-complicating it.

Try the following regular expression: ^(\/\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");
      }
   }
}
Related