Skip to content

Commit

Permalink
Precompile regular expression in
Browse files Browse the repository at this point in the history
InetAddressValidator.isValidInet6Address(String).
  • Loading branch information
garydgregory committed Oct 26, 2023
1 parent 6efff0f commit b8a1137
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
3 changes: 3 additions & 0 deletions src/changes/changes.xml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="ggregory" due-to="Andrés Torres">
Javadoc typos #144.
</action>
<action type="fix" dev="ggregory" due-to="Gary Gregory">
Precompile regular expression in InetAddressValidator.isValidInet6Address(String).
</action>
<!-- ADD -->
<action type="add" dev="ggregory" due-to="Dependabot, Gary Gregory">
Add github/codeql-action.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
* <p><b>InetAddress</b> validation and conversion routines (<code>java.net.InetAddress</code>).</p>
Expand Down Expand Up @@ -61,6 +62,9 @@ public class InetAddressValidator implements Serializable {

/** IPv4 RegexValidator */
private final RegexValidator ipv4Validator = new RegexValidator(IPV4_REGEX);

private static final Pattern DIGITS_PATTERN = Pattern.compile("\\d{1,3}");
private static final Pattern ID_CHECK_PATTERN = Pattern.compile("[^\\s/%]+");

/**
* Returns the singleton instance of this validator.
Expand Down Expand Up @@ -134,7 +138,7 @@ public boolean isValidInet6Address(String inet6Address) {
return false; // can only have one prefix specifier
}
if (parts.length == 2) {
if (!parts[1].matches("\\d{1,3}")) {
if (!DIGITS_PATTERN.matcher(parts[1]).matches()) {
return false; // not a valid number
}
final int bits = Integer.parseInt(parts[1]); // cannot fail because of RE check
Expand All @@ -149,7 +153,7 @@ public boolean isValidInet6Address(String inet6Address) {
}
// The id syntax is implementation independent, but it presumably cannot allow:
// whitespace, '/' or '%'
if (parts.length == 2 && !parts[1].matches("[^\\s/%]+")) {
if (parts.length == 2 && !ID_CHECK_PATTERN.matcher(parts[1]).matches()) {
return false; // invalid id
}
inet6Address = parts[0];
Expand Down

0 comments on commit b8a1137

Please sign in to comment.