String Replace Is Literal Not Regex
String.replace treats the target as literal text while replaceAll compiles a regex, so a plain dot replaces itself or swallows every character.
Code
import java.util.regex.Pattern;
public class DotReplacer {
public static void main(String[] args) {
String config = "app.config.v2.backup";
// String.replace 是 literal 替换:点号不是正则元字符
System.out.println(config.replace(".", "_"));
System.out.println(config.replace('.', '_'));
// String.replaceAll 才是 regex:点号匹配任意字符
System.out.println(config.replaceAll(".", "_"));
// 想按 regex 替换字面点号:转义或 quote
System.out.println(config.replaceAll("\\.", "_"));
System.out.println(config.replaceAll(Pattern.quote("."), "_"));
}
}How the snippet works
The moving parts are the class DotReplacer and the function main.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
Entry signature: public static void main(String[] args)
Key statements
String config = "app.config.v2.backup";
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
FAQ
- How do you run String Replace Is Literal Not Regex?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.