Regular Expressions, Literal Strings and Backslashes
by, 04-26-2012 at 06:55 PM (1334 Views)
In literal strings, backlash is considered as escape character. It is basically a single backlash i.e. “\\”. Backlash is also considered an escape character in case of regular expressions. A single backlash is matched to the regular expression \\. As a java string, regular expression would become “\\\\”. Four backlashes are used for matching just one single.
Word character is being matched with regex \w. It is abbreviated as "\\w".
Similar backlash mess up occurs, when replacement strings are provided for the methods, for example String.replaceAll() in your java code. In case of replacement text it is necessary to encode dollar sign as \$, or backlas as \\ when regex match is required to be replaced with backlash or dollar sign. In literal java strings, it is necessary to escape the backlashes. Hence in replacement text dollar sign would become \\$, when it is being written as literal string. One backlash would become \\\\. Four backlases are used for insertion of single one.