Java Regular Expression using slash

Viewed 87

My String is "T1/T2\/T3/T4\\/T5\\" My Expected output is "T1","T2/T3","T4\", "T5\"(split using /). if / is prefixed by \ then that / is treated as string character not a separator.

I am following the below code, `

    String pattern = "((?!/)(\\/|[^/])+(?=/)?)+";
    Pattern r = Pattern.compile(pattern);
    String path = {getting from request}; //Raw type T1/T2\/T3/T4\\/T5\\
    Matcher m = r.matcher(path);
    while (m.find()) {
        System.out.println(m.group(0));
    }`

my result is "T1/T2/T3/T4\/T5\" it is not an expected output. How I can change my regular expression so that it will give expected result? in backend my string will change since I am sending ?

2 Answers
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex
{
    public static void main(String[] args)
    {
        String pattern = "((?!/)(\\\\/|[^/])+(?=/)?)+";
        Pattern r = Pattern.compile(pattern);
        String path = args[0];
        Matcher m = r.matcher(path);
        while (m.find()) {
            System.out.println(m.group(0));
        }
    }
}

If you pass a literal string T1/T2\/T3/T4 as input you can use

String path = "T1/T2\\/T3/T4"; // <-- Note how the string must be coded in Java
String pattern = "(?s)(?:\\\\.|[^\\\\/])+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(path);
    while (m.find()) {
    System.out.println(m.group(0));
}
// => T1
//    T2\/T3
//    T4

See the Java demo and the regex demo.

Details:

  • (?s) - a Pattern.DOTALL flag option
  • (?:\\.|[^\\/])+ - a non-capturing group, one or more occurrences that matches either of the two patterns:
    • \\. - any single char escaped with a backslash
    • [^\\/] - any char other than / and a backslash.
Related