A
Avshi
I'm trying to validate a replacement string during construction time,
but the only way I found is really ugly. Please let me know if there's
a better way.
Thank you,
Avshi Avital
This is how I do it:
/**
* Verifying the replacement string is a bit awkward,
* because the only way to do this is to run the
* replacement string on a text that the regex matches
* and see if an exception is thrown.
* We chit by counting the number of capturing groups
* in the regex and then creating a fake regex that
* contains that many capturing groups. Since we
* construct the (fake) regex, we can also produce a
* text that matches it.Running the replacement string
* on that text tests its validity.
*/
private void verifyReplacementString(Pattern, pattern,
String replacement)
{
int groupCount = pattern.matcher("").groupCount();
StringBuffer sb = new StringBuffer();
sb.append(".*");
for (int i = 0; i < groupCount; i++) {
sb.append("()");
}
// This should throw if the replacement is invalid.
try {
Pattern.compile(
sb.toString()).matcher("").replaceAll(replacement);
} catch (IndexOutOfBoundsException e) {
throw new IllegalStateException(
"Replacement string \""+replacement +
"\" is illegal for regex \"" +
pattern.pattern()+"\"");
}
}
but the only way I found is really ugly. Please let me know if there's
a better way.
Thank you,
Avshi Avital
This is how I do it:
/**
* Verifying the replacement string is a bit awkward,
* because the only way to do this is to run the
* replacement string on a text that the regex matches
* and see if an exception is thrown.
* We chit by counting the number of capturing groups
* in the regex and then creating a fake regex that
* contains that many capturing groups. Since we
* construct the (fake) regex, we can also produce a
* text that matches it.Running the replacement string
* on that text tests its validity.
*/
private void verifyReplacementString(Pattern, pattern,
String replacement)
{
int groupCount = pattern.matcher("").groupCount();
StringBuffer sb = new StringBuffer();
sb.append(".*");
for (int i = 0; i < groupCount; i++) {
sb.append("()");
}
// This should throw if the replacement is invalid.
try {
Pattern.compile(
sb.toString()).matcher("").replaceAll(replacement);
} catch (IndexOutOfBoundsException e) {
throw new IllegalStateException(
"Replacement string \""+replacement +
"\" is illegal for regex \"" +
pattern.pattern()+"\"");
}
}