Home > DeveloperSection > Forums > Java RegEX To Split and Reverse String
Tanuj Kumar

Total Post:134

Points:940
Posted on    September-28-2013 4:21 AM

 JavaScript JavaScript 
Ratings:


 1 Reply(s)
 2029  View(s)
Rate this:
I have a Java String "test/this/string" that I want to reverse to "string/this/test" using a regular expression or the most efficient Java algorithm. The way I know is to use the split method, loop over the array and rebuild the string manually. The number of "/" can vary and doesn't occur a fixed number of times. Any ideas?


Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    September-28-2013 6:48 AM

Hey Tanuja!

Here's my take:

String input = "test/this/string";
List<String> list = Arrays.asList(input.split("(?=/)|(?<=/)"));
Collections.reverse(list);
StringBuilder sb = new StringBuilder();
for (String s: list)
   sb.append(s);
System.out.println(sb.toString());

(?<=/) is a zero-length matching regex that matches if the previous character is a /.
(?=/) is a zero-length matching regex that matches if the next character is a /.

So (?=/)|(?<=/) matches right before and after each /, thus the split splits the string into"test", "/", "this", "/", "string".


Don't want to miss updates? Please click the below button!

Follow MindStick