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.

Roshan
  • 2,019
  • 8
  • 36
  • 56
  • @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 – Roshan Sep 28 '16 at 02:36
  • Sorry - dumb comment – Scary Wombat Sep 28 '16 at 02:37
  • want to show some code you have tried. – Scary Wombat Sep 28 '16 at 02: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. – Roshan Sep 28 '16 at 02: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 ')'`. – Andreas Sep 28 '16 at 03:17
  • This can be done is a single regex, if you don't mind making it large. See [regex101](https://regex101.com/r/6h6txr/1) for demo. – Andreas Sep 28 '16 at 03:23
  • in case of 10 the regex looks ok. In case,if my logic shifts to 50 or 100 then it is unmaintainable – Roshan Sep 28 '16 at 05:11

2 Answers2

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);
Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35
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.

Community
  • 1
  • 1
vladsch
  • 606
  • 6
  • 7