7

Hello I was trying to use Java regular expression to get the required context path from the following path information.

String path = "/Systems/lenovo/";

I want to write regular expression to get "/Systems" and "/lenovo" separately.

I tried the following regular expression using groups but not working as expected.

String systemString = path.replaceAll("(.*)(/\\w+)([/][\\w+])", "$2") - to get "/Systems" - not working

String lenovoString = path.replaceAll("(.*)(/\\w+)([/][\\w+])", "$3") - to get "/lenovo" - working.

Could any body tell me what might be the wrong in my Regx?

M.S.Naidu
  • 2,239
  • 5
  • 32
  • 56

5 Answers5

3

You can try

String PATH_SEPARATOR = "/"; 
String str = "/Systems/lenovo/";
String[] res = str.substring(1).split(PATH_SEPARATOR);

IDEONE DEMO

And if you want to retain the / before the string then you can simply add it like:

"/"+res[0]

IDEONE DEMO

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

Just split like this:

String[] parts = path.replaceAll("/$", "").split("(?=/)");

The replaceAll() call is to remove the trailing slash (if any).

See live demo of

String path = "/Systems/lenovo/";
String[] parts = path.replaceAll("/$", "").split("(?=/)");
Arrays.stream(parts).forEach(System.out::println);

producing

/Systems
/lenovo
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

You shouldn't use this replaceAll with groups ($3) approach to get what you want.

What happens behind the scene with your approach is:

regex (.*)(/\\w+)([/][\\w+]) matches the string /Systems/l

Your expression is divided into the following groups:

$1 => (.*)
$2 => (/\\w+)
$3 => ([/][\\w+])

Each group matched the following part of your matched string /Systems/l

$1 => ''
$2 => /Systems
$3 => /l

So when you do

path.replaceAll("(.*)(/\\w+)([/][\\w+])", "$3")

you are essentially doing

'/Systems/lenovo/'.replaceAll(`/Systems/l`, '/l') => '/lenovo'

And when you use $2

'/Systems/lenovo/'.replaceAll(`/Systems/l`, '/Systems') => '/Systemsenovo/'

So it doesn't really make sense to use regex groups for this task and better use simple String.split method as others suggested on this page

jonasnas
  • 3,540
  • 1
  • 23
  • 32
0

You can try this:

String path = "/Systems/lenovo/";
String[] arr = path.split("/");
String str1 = "/"+arr[1];
String str2 = "/"+arr[2];
System.out.println("str1 = " + str1);
System.out.println("str2 = " + str2);

And the result:

str1 = /Systems
str2 = /lenovo
Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68
0

To get /Systems, you need this regex: (?:\/[^\/]+) and for /lenovo, you need: (?:\/[^\/]+){1}(?=\/$)

You can try this (see http://ideone.com/dB3edh):

   String path = "/Systems/lenovo/";
    Pattern p = Pattern.compile("(?:\\/[^\\/]+)");
    Matcher m = p.matcher(path);

    if(m.find()) {
        System.out.println(m.group(0));
    }
    p = Pattern.compile("(?:\\/[^\\/]+){1}(?=\\/$)");
    m = p.matcher(path);
    if(m.find()) {
        System.out.println(m.group(0));
    }
amekki
  • 128
  • 1
  • 9