jamal
jamal

Reputation: 53

How to combine two javascript regular expression or regex

I want to combine the two regex.

/^([a-z]{2})?([0-9]+)$/gi and /^(?!.*?([0-9])\1{3})\S+$/gi

something like this /(([a-z]{2})?([0-9]+)) || ((?!.*?([0-9])\1{3})\S+)/gi and this /(([a-z]{2})?([0-9]+)) && ((?!.*?([0-9])\1{3})\S+)/gi

So I need both the above two separate regex combined in one regex format.

I need both or(||) as well as and(&&).

what the above regex code actually does is:

Below is to check for, not allow more than 3 same character:

/^(?!.*?([0-9])\1{3})\S+$/gi.test("4444") => false
/^(?!.*?([0-9])\1{3})\S+$/gi.test("11222") => true
/^(?!.*?([0-9])\1{3})\S+$/gi.test("77722") => true

Below is for to check, not more than 2 characters at beginning and followed by only numbers:

/^(([a-z]{1,2})?([0-9]+))$/gi.test('sj76755') => true
/^(([a-z]{1,2})?([0-9]+))$/gi.test('k4545') => true
/^(([a-z]{1,2})?([0-9]+))$/gi.test('6j53') => false
/^(([a-z]{1,2})?([0-9]+))$/gi.test('653aa') => false
/^(([a-z]{1,2})?([0-9]+))$/gi.test('ss653aa') => false

So I need both the above two separate regex combined in one regex format.

I need both or(||) as well as and(&&).

Thanks in advance

Upvotes: 0

Views: 123

Answers (1)

user13469682
user13469682

Reputation:

OP Curr regex's :
( ^(?!.*?([0-9])\1{3})\S+$ , ^(([a-z]{1,2})?([0-9]+))$ )

The AND :
note - The minimum is the subset that includes both is the only required, dissallow others.
In this case, the two regex minimums are ^\S+$ , ^[a-z]{0,2}[0-9]+$
where the subset that satisfies both is ^[a-z]{0,2}[0-9]+$.

After applying the assershun we find the AND regex resolves to this

^(?!.*?([0-9])\1{3})[a-z]{0,2}[0-9]+$

demo1

The OR :
note - Each regex has it's own pecularity's that make it dificult to
merge functionality. It is possible though to just factor out common
terms that satisfy both.
Each need to be joined with an or metachar |.
But, each situation is different, it takes an experienced developer (me)
to find the possibilities.

After factoring we find the OR regex resolves to this

^(?:(?!.*?([0-9])\1{3})\S+|[a-z]{0,2}[0-9]+)$

demo2


OP Prev regex's :
The OR ^([a-z]{2})?([0-9]+)$|[0-9]{4,}

The AND ^([a-z]{2})?([0-9]{4,})$

Upvotes: 1

Related Questions