How to use Java regular expression to check if a string follows a certain pattern ? eg to check if a message first starts with " In the morning
", then followed by any words, then followed by " In the afternoon
", and then followed by any words.
I have tried to look up the regex syntax but found it difficult to understand.
I have tried to use |
, but this is an "Or" operator. And it does not specify the ordering of first matching " In the morning
" and then " In the afternoon
".
Pattern pattern = Pattern.compile("\\bIn the morning\\b|\\bIn the afternoon\\b");
Matcher matcher = pattern.matcher("In the morning I read the news, then I start my work. In the afternoon I have my lunch.");
^In the morning .*In the afternoon.*
The ^ matches the start of the expression to match. The .* matches zero or more non return characters.
You can also put parenthesis around the .* to form capture groups to find out what actually you did in the morning and afternoon
^In the morning (.*)In the afternoon (.*)
String str = "In the morning I read the news, then I start my work. In the afternoon I have my lunch.";
Pattern pattern = Pattern.compile("^\\bIn the morning\\b.*\\bIn the afternoon\\b.*$");
Matcher matcher = pattern.matcher(str);
if (matcher.matches())
System.out.println("match");
else
System.err.println("not match");
^
asserts position at the start of a line \\b
assert position at a word boundary: (^\\w|\\w$|\\W\\w|\\w\\W)
.
matches any character (except for line terminators)*
matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy) $
asserts position at the end of a line I think you want .*
in between the two phrases, rather than an alternation. Try this version:
Pattern pattern = Pattern.compile("\\bIn the morning\\b.*\\bIn the afternoon\\b");
Matcher matcher = pattern.matcher("In the morning I read the news, then I start my work. In the afternoon I have my lunch.");
if (matcher.find()) {
System.out.println(matcher.group());
}
This prints:
In the morning I read the news, then I start my work. In the afternoon
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.