开发者

How to make a Regex that specifies elements in any order?

I want a regex that matches a string which contains

 - 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 that all the following would be matched:

<p>{123

2}</p>

2<p>}}}

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

And none of these would be matched:

<p>{ alphabet 123

{2}

{{{}}}

<p>1</p>

Here's what I have so far, which demands only one of any of those components:

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

My problem is that I don't know how to make it more general without also having to specify the order like this:

(开发者_如何学JAVA<\/p>|<p>)+(\d)+(\}|\{)+

Or making it stupidly long to enumerate every possible order...

How can I say "Needs at least one of each of these components in any order?"

Thanks.


If your regex flavor supports lookaheads, you can use positive lookahead as:

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

This regex uses positive lookahead to assert that the string as atleast one of either { or }, at least one digit and atleast one of either <p> or </p>.

If you want to ensure that the string has only these and nothing else can use the regex:

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

which works as previous regex but also ensures that the input has no other character.

Regex implemented in Perl

The regex can be made a bit shorter as:

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

which makes use of the fact that \{|\} is same as [{}], <p>|<\/p> is same as <\/?p>.


I guess you'll just have to check three expressions

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜