开发者

How do I match several strings in a text using Regular Expression?

开发者 https://www.devze.com 2023-04-02 17:43 出处:网络
I need a regular expression to validate a text for several strings that must be present. Say I have the texts

I need a regular expression to validate a text for several strings that must be present. Say I have the texts

  1. Rosy made the boys go w开发者_运维技巧ild
  2. Marys wild boys are very crazy indeed
  3. Henry is a wild boy
  4. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消