Reputation: 141
I have a String that contains new line characters say...
str = "Hello\n"+"Batman,\n" + "Joker\n" + "here\n"
I would want to know how to find the existance of a particular word say .. Joker
in the string str
using java.lang.String.matches()
I find that str.matches(".*Joker.*")
returns false
and returns true
if i remove the new line characters. So what would be the regex expression to be used as an argument to str.matches()
?
One way is... str.replaceAll("\\n","").matches(.*Joker.*);
Upvotes: 1
Views: 2080
Reputation: 121702
The problem is that the dot in .*
does not match newlines by default. If you want newlines to be matched, your regex must have the flag Pattern.DOTALL
.
If you want to embed that in a regex used in .matches()
the regex would be:
"(?s).*Joker.*"
However, note that this will match Jokers
too. A regex does not have the notion of words. Your regex would therefore really need to be:
"(?s).*\\bJoker\\b.*"
However, a regex does not need to match all its input text (which is what .matches()
does, counterintuitively), only what is needed. Therefore, this solution is even better, and does not require Pattern.DOTALL
:
Pattern p = Pattern.compile("\\bJoker\\b"); // \b is the word anchor
p.matcher(str).find(); // returns true
Upvotes: 2
Reputation: 4191
You want to use a Pattern that uses the DOTALL flag, which says that a dot should also match new lines.
String str = "Hello\n"+"Batman,\n" + "Joker\n" + "here\n";
Pattern regex = Pattern.compile("".*Joker.*", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(str);
if (regexMatcher.find()) {
// found a match
}
else
{
// no match
}
Upvotes: 1
Reputation: 61128
You can do something much simpler; this is a contains
. You do not need the power of regex:
public static void main(String[] args) throws Exception {
final String str = "Hello\n" + "Batman,\n" + "Joker\n" + "here\n";
System.out.println(str.contains("Joker"));
}
Alternatively you can use a Pattern
and find
:
public static void main(String[] args) throws Exception {
final String str = "Hello\n" + "Batman,\n" + "Joker\n" + "here\n";
final Pattern p = Pattern.compile("Joker");
final Matcher m = p.matcher(str);
if (m.find()) {
System.out.println("Found match");
}
}
Upvotes: 1