Reputation: 2884
I want to make sure that the text is not a question type and also contains at least one of these:watch live watch speech live #breaking #breaking news
so I wrote the code as follow:
private static void containsQuestion(String commentstr){
String urlPattern = "^(?!.*?\\?)(watch live|watch speech live|#breaking|#breaking news)";
Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(commentstr);
if (m.find()) {
System.out.println("yes");
}
}
but when I try it with for example:
They say 2's company; is 3 a crowd watch live on...
I expect to see yes in the console since it is matched but nothing happens Why?
Upvotes: 1
Views: 32
Reputation: 785276
Problem is your use of start anchor ^
,
Either remove it:
String urlPattern =
"(?!.*?\\?)(watch live|watch speech live|#breaking|#breaking news)";
Or place .*?
before your keywords to match any # of chars before your phrases:
String urlPattern =
"^(?!.*?\\?).*?(watch live|watch speech live|#breaking|#breaking news)";
Due to use of ^
your regex is trying to match all those phrases only at start.
Upvotes: 1
Reputation: 4075
You need to allow more characters before/after you key words: Try this:
/^(?!.*?\?).*(watch live|watch speech live|\#breaking|\#breaking news).*/gm
https://regex101.com/r/uS1xQ4/2
Upvotes: 0