85 lines
1.9 KiB
Plaintext
85 lines
1.9 KiB
Plaintext
== Why is this an issue?
|
|
|
|
include::../description.adoc[]
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
String date = "01/02";
|
|
|
|
Pattern datePattern = Pattern.compile("(?<month>[0-9]{2})/(?<year>[0-9]{2})");
|
|
Matcher dateMatcher = datePattern.matcher(date);
|
|
|
|
if (dateMatcher.matches()) {
|
|
checkValidity(dateMatcher.group(1), dateMatcher.group(2)); // Noncompliant - numbers instead of names of groups are used
|
|
checkValidity(dateMatcher.group("day")); // Noncompliant - there is no group called "day"
|
|
}
|
|
|
|
// ...
|
|
|
|
String score = "14:1";
|
|
|
|
Pattern scorePattern = Pattern.compile("(?<player1>[0-9]+):(?<player2>[0-9]+)"); // Noncompliant - named groups are never used
|
|
Matcher scoreMatcher = scorePattern.matcher(score);
|
|
|
|
if (scoreMatcher.matches()) {
|
|
checkScore(score);
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
String date = "01/02";
|
|
|
|
Pattern datePattern = Pattern.compile("(?<month>[0-9]{2})/(?<year>[0-9]{2})");
|
|
Matcher dateMatcher = datePattern.matcher(date);
|
|
|
|
if (dateMatcher.matches()) {
|
|
checkValidity(dateMatcher.group("month"), dateMatcher.group("year"));
|
|
}
|
|
|
|
// ...
|
|
|
|
String score = "14:1";
|
|
|
|
Pattern scorePattern = Pattern.compile("(?<player1>[0-9]+):(?<player2>[0-9]+)");
|
|
Matcher scoreMatcher = scorePattern.matcher(score);
|
|
|
|
if (scoreMatcher.matches()) {
|
|
checkScore(scoreMatcher.group("player1"));
|
|
checkScore(scoreMatcher.group("player2"));
|
|
}
|
|
----
|
|
Or, using dedicated variables instead of group names:
|
|
|
|
[source,java]
|
|
----
|
|
String score = "14:1";
|
|
|
|
String player = "([0-9]+)";
|
|
String gameScore = player + ":" + player;
|
|
|
|
Pattern scorePattern = Pattern.compile(gameScore);
|
|
Matcher scoreMatcher = scorePattern.matcher(score);
|
|
|
|
if (scoreMatcher.matches()) {
|
|
checkScore(score);
|
|
}
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
include::highlighting.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|