kamaci
kamaci

Reputation: 75137

Java Regex Doesn't Work For Characters As Like \n

I want to remove all characters that starts with {{ and ends with }} I've written that regex:

String templatePattern = "\\{\\{.*?\\}\\}";

and I use that:

text.replaceAll(templatePattern, "");

It works but for strings as like that:

{{Apple \n banana }}

it doesn't work. If I replace all \n characters with space character it works. What is the proper solution for it? Because I should apply same thing for \t and others too.

Upvotes: 0

Views: 117

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213243

The reason is, a dot matches anything but \n. If you want to match everything, then you can use [\s\S], or [\w\W] or any such variations of complimenting meta-characters:

String templatePattern = "\\{\\{[\s\S]*?\\}\\}";

Another way is to make the dot actually match the newline, by using (?s) flag:

String templatePattern = "(?s)\\{\\{.*?\\}\\}";

The later one is indeed a better way. (?s) is same as Pattern.DOTALL.

Upvotes: 6

Related Questions