Ari
Ari

Reputation: 7556

Check if there is a match between a string and all of a given set of regular expressions

I know one can use OR operator on regular expressions:

$str = "Here is a strawhat, some cranberry, and a strawberry!";
while($str =~ /(\bstraw\B|\Bberry\b)/g) {
  print "Thanks for the $& !\n";
}

Is there a simple and short way other than a while loop to AND them instead of OR, so that the only match is "strawberry"?

In other words, I need to check if there exists a substring in a string that matches all of the given regular expressions.

Upvotes: 2

Views: 171

Answers (1)

Sean
Sean

Reputation: 29790

If I'm understanding your question correctly, you can use lookahead assertions for this:

if ($str =~ /^(?=.*?regexp-1)(?=.*?regexp-2)...(?=.*?regexp-n)/s) {
    # $str matches regexp-1, regexp-2, ..., regexp-n.
}

There are a couple of assumptions built into this construction:

  • All of the subexpressions are well-formed.
  • None of the subexpressions use the . metacharacter to mean "any character except a newline". You could turn this behavior back on with (?-s:...) as necessary.

Upvotes: 4

Related Questions