---
title: "Java RegEX To Split and Reverse String"  
description: "Java RegEX To Split and Reverse String"  
author: "Anonymous User"  
published: 2013-09-28  
updated: 2013-09-28  
canonical: https://www.mindstick.com/forum/1554/java-regex-to-split-and-reverse-string  
category: "javascript"  
tags: ["javascript"]  
reading_time: 1 minute  

---

# Java RegEX To Split and Reverse String

I have a Java [String](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) "test/this/string" that I want to [reverse](https://www.mindstick.com/blog/63740/what-are-the-most-effective-and-safest-thanks-to-reverse-erectile-dysfunction) to "string/this/test" using a [regular expression](https://www.mindstick.com/articles/11909/java-regex-or-regular-expression-in-java) or the most [efficient](https://www.mindstick.com/articles/33637/three-tips-for-an-energy-efficient-home-for-2019) Java algorithm. The way I know is to use the [split](https://www.mindstick.com/blog/11920/top-3-voltas-split-acs-for-your-home) [method](https://www.mindstick.com/forum/166/webservice-method), loop over the [array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net) and rebuild the string manually. The number of "/" can vary and doesn't occur a fixed number of times. Any [ideas](https://www.mindstick.com/articles/43878/making-the-best-use-of-the-options-trade-ideas)?

## Replies

### Reply by Anonymous User

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".


---

Original Source: https://www.mindstick.com/forum/1554/java-regex-to-split-and-reverse-string

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
