1

I want to match regex pattern in java for particular text. In that while matching I need to find matches in reverse order.

Example:

Regex Pattern --  [([^]]*])

Input String  -- [blue][red][green]

Output   --  1st match --->[blue]
             2nd match --->[red]
             3rd match --->[green]

But I'm expecting match to be in reverse order.

Expected output  --    1st match --->[green]
             2nd match --->[red]
             3rd match --->[blue]

Please help how to form the regex to achieve the expected output.

7
  • @ScaryWombat StringBuilder.reverse will reverse the String as whole like this ]neerg[]der[]eulb[. I don't know how it will solve my problem. Please explain me Commented Sep 28, 2016 at 2:36
  • Sorry - dumb comment Commented Sep 28, 2016 at 2:37
  • want to show some code you have tried. Commented Sep 28, 2016 at 2:37
  • Now i achieved by saving matches in ArrayList and reverse the List to get Expected output. But I need to do it in regex part itself. Because in case they are more than 10 matches I need only 10 matches from the last. So I iterate the reverse List for the size upto 10 and break the loop. I don't need to grow list size as it may contain 100 or 1000 matches. I need only last 10. Commented Sep 28, 2016 at 2:40
  • That regex doesn't work unless you add some escapes. [([^] is a character group matching (, [ or ^. Next is ]* matching 0 or more ]. Next is ] matching exactly one ]. Last is ) which causes PatternSyntaxException: Unmatched closing ')'. Commented Sep 28, 2016 at 3:17

2 Answers 2

1

Assuming you have complied regex date"

     ArrayList<String> strings = new ArrayList<>();
            Matcher foo = date.matcher("foo");
            while (foo.matches()) {
                strings.add(foo.group());
            }
            Collections.reverse(strings);
Sign up to request clarification or add additional context in comments.

Comments

0

Reverse regular expression in Java discusses the topic and I posted a solution there, added here for convenience.

If anyone is interested in a Java solution, I implemented a library to do just that. https://github.com/vsch/reverse-regex.

Handles all valid Java regex constructs and provides utility classes to wrap pattern, matcher and input for reverse searches to handle all need mappings and reversals.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.