How do I match several strings in a text using Regular Expression?
I need a regular expression to validate a text for several strings that must be present. Say I have the texts
- Rosy made the boys go w开发者_运维技巧ild
- Marys wild boys are very crazy indeed
- Henry is a wild boy
- Sally danced with 3 boys last night
And I want to Match the sentences that has both 'boys' AND 'wild' (in any order). The correct matches are 1 and 2, but not 3 and 4.
Anybody?
.*(?=\bboys\b).*(?=\bwild\b)|.*(?=\bwild\b).*(?=\bboys\b)
Regex is overkill here. This works fine and is more readable:
for (String str : new String[] { "Rosy made the boys go wild", "Marys wild boys are very crazy indeed",
"Henry is a wild boy", "Sally danced with 3 boys last night" }) {
if (str.contains("wild") && str.contains("boys")) {
System.out.println(str);
}
}
Prints:
Rosy made the boys go wild
Marys wild boys are very crazy indeed
http://www.regular-expressions.info/reference.html
/.*?wild.*?boys.*|.*?boys.*?wild.*/
You want to use the .*?
because just .*
alone is greedy and will consume the entire string. With a greedy match, you'll have no characters left to match against "wild" and "boys" so it will always fail.
(^.*boys.*wild.* $|^.*wild.*boys.*$)
With appropriate escaping depending on where you're using it, of course.
精彩评论