eszik.k
eszik.k

Reputation: 1781

How do I combine two regex statement with AND?

I have two regex statement which are working well separately.

First regex :

(.*[\w].*)//which means the test contains at least one non-special character.

Second regex:

.{3,}. //the text is greater than 3 character.

So I want two combine these two regex. To match text which are greater than 3 char AND contains at least one non-special character.

My test text:

asd //not match

asd@ //match

@@{{@}@{a //match

@@{}@{} //not match

*/*/*/*/+ not match

5542 // match

@{}43 //match

Upvotes: 0

Views: 136

Answers (2)

Michael Lorton
Michael Lorton

Reputation: 44416

I don't think there is a general way of intersecting two regexps, but this one could be re-phrased as an alternation (union), of

  • a non-special character, followed by three characters, or
  • a non-special character, preceded by two characters, or
  • a non-special character, preceded by two characters and followed by one character, or
  • a non-special character, preceded by one character and followed by two characters, or
  • a non-special character, preceded by thee characters

For example:

/.*\w...+|.+\w..+|.+.\w.+|...+\w.*/

(Another solution demonstrates a more general way to achieve something very like an AND.)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522292

One way you can achieve this is using a positive lookahead asserting that a non symbol character appears at least once in the pattern. Then match anything whose length is four or more (the assertion having already guaranteed that your non symbol character is present).

^(?=.*[\w].*).{4,}$

Explanation:

^(?=.*[\w].*)    assert that what follows the start of the string
                 includes one (or more) non symbol characters
.{4,}$           match any character four or more times

Demo here:

Regex101

Upvotes: 2

Related Questions