Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions its/ruling/src/test/resources/regex-examples/java-S9353.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"org.regex-examples:regex-examples:src/main/java/org/regex/examples/RegexDatabase2.java": [
457
],
"org.regex-examples:regex-examples:src/main/java/org/regex/examples/RegexDatabase8.java": [
1129
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package checks;

import java.util.regex.Pattern;

class BareDotRegexpCheckSample {

private static final String DOT = ".";
private static final String ESCAPED_DOT = "\\.";

void noncompliant(String filename) {
filename.split("."); // Noncompliant {{This regex "." matches any character, not a literal dot; escape it as "\\." if a period was intended.}}
// ^^^
filename.split(".", 2); // Noncompliant
filename.split(DOT); // Noncompliant
filename.replaceAll(".", "_"); // Noncompliant
filename.replaceFirst(".", "_"); // Noncompliant
filename.matches("."); // Noncompliant
Pattern.compile("."); // Noncompliant
Pattern.compile(DOT); // Noncompliant
Pattern.compile(".", Pattern.DOTALL); // Noncompliant
Pattern.matches(".", filename); // Noncompliant
}

void compliant(String filename, String regex, int flags) {
filename.split("\\.");
filename.split(ESCAPED_DOT);
filename.split(Pattern.quote("."));
filename.split("[.]");
filename.split(".*");
filename.split(regex);
filename.replace(".", "_");
filename.replaceAll("\\.", "_");
filename.replaceFirst("\\.", "_");
filename.matches("\\.");
Pattern.compile("\\.");
Pattern.compile(".", Pattern.LITERAL);
Pattern.compile(".", Pattern.LITERAL | Pattern.CASE_INSENSITIVE);
Pattern.compile(regex);
Pattern.compile(".", flags);
Pattern.matches("\\.", filename);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import java.util.regex.Pattern;
import org.sonar.check.Rule;
import org.sonar.java.checks.methods.AbstractMethodDetection;
import org.sonar.plugins.java.api.semantic.MethodMatchers;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.MethodInvocationTree;

@Rule(key = "S9353")
public class BareDotRegexpCheck extends AbstractMethodDetection {

private static final String MESSAGE = "This regex \".\" matches any character, not a literal dot; escape it as \"\\\\.\" if a period was intended.";
private static final String JAVA_LANG_STRING = "java.lang.String";
private static final String JAVA_UTIL_REGEX_PATTERN = "java.util.regex.Pattern";
private static final String COMPILE_METHOD_NAME = "compile";

private static final MethodMatchers REGEX_METHODS = MethodMatchers.or(
MethodMatchers.create()
.ofTypes(JAVA_LANG_STRING)
.names("split", "matches")
.addParametersMatcher(JAVA_LANG_STRING)
.build(),
MethodMatchers.create()
.ofTypes(JAVA_LANG_STRING)
.names("split")
.addParametersMatcher(JAVA_LANG_STRING, "int")
.build(),
MethodMatchers.create()
.ofTypes(JAVA_LANG_STRING)
.names("replaceAll", "replaceFirst")
.addParametersMatcher(JAVA_LANG_STRING, JAVA_LANG_STRING)
.build(),
MethodMatchers.create()
.ofTypes(JAVA_UTIL_REGEX_PATTERN)
.names("matches")
.addParametersMatcher(JAVA_LANG_STRING, "java.lang.CharSequence")
.build(),
MethodMatchers.create()
.ofTypes(JAVA_UTIL_REGEX_PATTERN)
.names(COMPILE_METHOD_NAME)
.addParametersMatcher(JAVA_LANG_STRING)
.build(),
MethodMatchers.create()
.ofTypes(JAVA_UTIL_REGEX_PATTERN)
.names(COMPILE_METHOD_NAME)
.addParametersMatcher(JAVA_LANG_STRING, "int")
.build());

@Override
protected MethodMatchers getMethodInvocationMatchers() {
return REGEX_METHODS;
}

@Override
protected void onMethodInvocationFound(MethodInvocationTree mit) {
ExpressionTree regexArgument = mit.arguments().get(0);
if (isBareDot(regexArgument) && !isLiteralPattern(mit)) {
reportIssue(regexArgument, MESSAGE);
}
}

private static boolean isBareDot(ExpressionTree regexArgument) {
return regexArgument.asConstant(String.class).filter("."::equals).isPresent();
}

private static boolean isLiteralPattern(MethodInvocationTree mit) {
if (mit.arguments().size() < 2 || !COMPILE_METHOD_NAME.equals(mit.methodSymbol().name())) {
return false;
}
return mit.arguments().get(1).asConstant(Integer.class)
.map(flags -> (flags & Pattern.LITERAL) != 0)
.orElse(true);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath;

class BareDotRegexpCheckTest {

@Test
void test() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/BareDotRegexpCheckSample.java"))
.withCheck(new BareDotRegexpCheck())
.verifyIssues();
}

@Test
void test_without_semantic() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/BareDotRegexpCheckSample.java"))
.withCheck(new BareDotRegexpCheck())
.withoutSemantic()
.verifyIssues();
}
Comment thread
gitar-bot[bot] marked this conversation as resolved.

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<p>In Java regular expressions, <code>.</code> is a metacharacter that matches any single character, not a literal period.</p>
<p>Passing <code>"."</code> to regex APIs such as <code>String.split</code>, <code>String.replaceAll</code>, <code>String.replaceFirst</code>,
<code>String.matches</code>, <code>Pattern.compile</code>, or <code>Pattern.matches</code> therefore does not treat the argument as a dot separator.
Developers almost always intended a literal <code>'.'</code>.</p>
<h2>Why is this an issue?</h2>
<p><code>String.split</code> and <code>Pattern.compile</code> interpret their pattern argument as a regular expression. A pattern that is exactly
<code>"."</code> matches every character.</p>
<p>This is especially surprising with <code>String.split</code>: <code>"archive.tar.gz".split(".")</code> matches each character as a delimiter.
Trailing empty strings are discarded, so the result is an empty array rather than <code>["archive", "tar", "gz"]</code>.</p>
<p>The same pattern is just as wrong with replacement APIs. <code>"report.2026.pdf".replaceAll(".", "x")</code> replaces every character with
<code>x</code>, instead of replacing only the dots.</p>
<p>To match a literal period, escape the metacharacter (<code>"\\."</code>), quote it (<code>Pattern.quote(".")</code>), or use a non-regex API such
as <code>String.replace</code>.</p>
<h3>Exceptions</h3>
<p>This rule does not raise an issue when <code>Pattern.compile</code> is called with the <code>Pattern.LITERAL</code> flag, because that flag treats
the pattern as a literal string.</p>
<p>If matching any character is intentional, add an inline <code>// NOSONAR: "." intentionally matches any character</code> comment so the intent is
explicit.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
String filename = "archive.tar.gz";
String[] parts = filename.split("."); // Noncompliant: matches every character instead of a literal '.'
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
String filename = "archive.tar.gz";
String[] parts = filename.split("\\.");
</pre>
<h4>Noncompliant code example</h4>
<pre data-diff-id="2" data-diff-type="noncompliant">
String filename = "report.2026.pdf";
String sanitized = filename.replaceAll(".", "_"); // Noncompliant: replaces every character
String first = filename.replaceFirst(".", "_"); // Noncompliant
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="2" data-diff-type="compliant">
String filename = "report.2026.pdf";
String sanitized = filename.replace(".", "_");
String first = filename.replaceFirst("\\.", "_");
</pre>
<h4>Noncompliant code example</h4>
<pre data-diff-id="3" data-diff-type="noncompliant">
Pattern dots = Pattern.compile("."); // Noncompliant: compiles a match-any-character pattern
boolean dotted = Pattern.matches(".", "a"); // Noncompliant
boolean oneChar = "a".matches("."); // Noncompliant
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="3" data-diff-type="compliant">
Pattern dots = Pattern.compile("\\.");
boolean dotted = Pattern.matches("\\.", "a");
boolean oneChar = "a".matches("\\.");
</pre>
<h4>Noncompliant code example</h4>
<pre data-diff-id="4" data-diff-type="noncompliant">
Pattern anyChar = Pattern.compile("."); // Noncompliant
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="4" data-diff-type="compliant">
Pattern anyChar = Pattern.compile("."); // NOSONAR: "." intentionally matches any character
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li>Java Documentation - <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/regex/Pattern.html#sum">Summary of
regular-expression constructs</a></li>
<li>Java Documentation - <a
href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html#split(java.lang.String)"><code>String.split</code>
method</a></li>
<li>Java Documentation - <a
href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/regex/Pattern.html#quote(java.lang.String)"><code>Pattern.quote</code>
method</a></li>
</ul>
<h3>Related rules</h3>
<ul>
<li>{rule:java:S2639} - Inappropriate regular expressions should not be used</li>
<li>{rule:java:S5361} - "String#replace" should be preferred to "String#replaceAll"</li>
</ul>

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"title": "A bare \".\" should not be used as a regular expression",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"regex"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-9353",
"sqKey": "S9353",
"scope": "All",
"quickfix": "targeted",
Comment thread
gitar-bot[bot] marked this conversation as resolved.
"code": {
"impacts": {
"RELIABILITY": "MEDIUM"
},
"attribute": "LOGICAL"
}
}
Empty file.
Loading