How to create a regex that indicates elements in any order?

I want a regular expression that matches a string containing

 - At least one brace: } or {  
and
 - At least one digit: \d  
and
 - At least one instance of either: <p> or </p>

But in any order, so all of the following will match:

<p>{123

2}</p>

2<p>}}}

{}{}{}<p></p></p>234234}}}

And not one of them will match:

<p>{ alphabet 123

{2}

{{{}}}

<p>1</p>

Here is what I still have, which requires only one of these components:

(<\/p>|<p>|\d|\}|\{)+

My problem is that I don’t know how to make it more general without specifying the order:

(<\/p>|<p>)+(\d)+(\}|\{)+

Or make it silly to list all possible orders for a long time ...

How can I say: "At least one of these components is required in any order?"

Thank.

+3
source share
2 answers

If your regex flavor supports lookaheads, you can use positive browsing like:

^(?=.*(\{|\}))(?=.*\d)(?=.*(<p>|<\/p>)).*$

lookahead, , { }, <p> </p>.

, :

^(?=.*(\{|\}))(?=.*\d)(?=.*(<p>|<\/p>))(<\/p>|<p>|\d|\}|\{)*$

, , .

Regex Perl

, :

^(?=.*[{}])(?=.*\d)(?=.*<\/?p>)(<\/?p>|[\d}{])*$

, \{|\} [{}], <p>|<\/p> <\/?p>.

+5

,

0

Source: https://habr.com/ru/post/1775113/


All Articles