GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Use of String#replaceAll with a first argument which is not a regular expression — CodeQL query help documentation

Use of String#replaceAll with a first argument which is not a regular expression¶

ID: java/string-replace-all-with-non-regex
Kind: problem
Security severity: 
Severity: recommendation
Precision: very-high
Tags:
   - quality
   - reliability
   - performance
   - external/cwe/cwe-1176
Query suites:
   - java-code-quality.qls

Click to see the query in the CodeQL repository

Overview¶

The String#replaceAll method is designed to work with regular expressions as its first parameter. When you use a simple string without any regex patterns (like special characters or syntax), it’s more efficient to use String#replace instead. This is because replaceAll has to compile the input as a regular expression first, which adds unnecessary overhead when you are just replacing literal text.

Recommendation¶

Use String#replace instead where a replaceAll call uses a trivial string as its first argument.

Example¶

public class Test {
    void f() {
        String s1 = "test";
        s1 = s1.replaceAll("t", "x"); // NON_COMPLIANT
        s1 = s1.replaceAll(".*", "x"); // COMPLIANT
        s1 = s1.replace("t", "x"); // COMPLIANT
    }
}

References¶

  • Java SE Documentation: String.replaceAll.

  • Common Weakness Enumeration: CWE-1176.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.