views:

26

answers:

1

I have developed a UI that allows users to define a regex pattern and then a replacement string that is used by appendReplacement().

e.g.

  • Pattern - 7(.*)
  • Replace pattern - $1

So 71234 would yield 1234.

Is there anyway I can verify that the input pattern and replace pattern are compatible without the user having to enter a matching string? For example if the replace pattern was $1$2 then this would throw an exception at runtime. Can I check for this in advance?

EDIT:

Final solution was to do as aioobe suggested and get the group count by creating a dummy Matcher (not sure why this method isn't on Pattern TBH) and then manually parsing the replace string manually to find which $ group references are present. Bit fiddly but works.

+2  A: 

Well, you could do something like:

yourPattern.matcher("").groupCount();

groupCount() will return the number of capturing groups (which at least can be thought of as an upper limit of what the user may refer to).

aioobe
Thanks, can I then verify that against the replace pattern to ensure $2 isn't present if there's only one group?
Mike Q
Yes. That would seem like a good idea.
aioobe
Note that there still may be groups that evaluate to null based on the actual text being matched. For example, the pattern `(a)|(b)` has 2 groups, but only one of them will match the text.
Avi
Good point! ...
aioobe
@Avi, that's fine in my case as I'm just wanting to validate that there are no $ back references that point to a non-existent group.
Mike Q