Sensei Logo Sensei Hub

Recipe - Strings: Regex Use: Escape Regex Special Character for Any Char Matching

Description:
First argument is a regular expression, matching with dot might have unintended behaviour.
Level:
error
Language:
  • java
Tags:
  • security
  • Java basic
Documentation

String's split method takes a regular expression as argument. The character '.' has a special meaning in regexes.

When trying to split by "." we will not get the result we expect. Instead every character in the String will be used as a split point, resulting in an empty array. We need to use "\\." instead i.e. the . escaped in a String.

Before:
String[] parts = "123.456.789.012".split(".");
After:
String[] parts = "123.456.789.012".split("\\.");
Recipe
id: scw:java:string-split-dot-regex
version: 10
metadata:
  name: 'Strings: Regex Use: Escape Regex Special Character for Any Char Matching'
  shortDescription: First argument is a regular expression, matching with dot might have unintended behaviour.
  level: error
  language: java
  enabled: true
  descriptionFile: descriptions/StringsRegexUseEscapeRegexSpecialCharacterforAnyCharMatching.html
  tags: security;Java basic
search:
  methodcall:
    args:
      1:
        value:
          stringified: "."
    name:
      matches: (split|replaceAll|replaceFirst)
    declaration:
      type: java.lang.String
availableFixes:
- name: Escape the regex special character for any char
  actions:
  - modifyArguments:
      rewrite:
        1: '"\\."'