0

I want to concatenate two Regular expressions with AND operator (I don't know if this is possible ... ) so the match happens only when the string matches RegEx1 and RegEx2.

 RegEx1: [a-g]+
 RegEx2: [b-z]+
 Example1 : String "bcd" match 
 Example2 : String "hijk" not match 

It was easy with OR operator, but for AND I could not find a solution.

Ayoub Abid
  • 432
  • 5
  • 15

2 Answers2

1

Use a positive lookahead combined with 'start and end of string' anchors to ensure entire string is matched and no "illegal" letters are present:

^(?=[a-g]+$)(?=[b-z]+$).*

https://regex101.com/r/Bz7qnb/2/

Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
0

You can use the positive look-ahead operator (?=) to combine expressions:

(?=[a-g]+)(?=[b-z]+)

Here is a fiddle to test it: https://regex101.com/r/kyy6XZ/1

In this case, it's logically equivalent to [b-g]+, which means it should match any string that has a letter or more in the b to g interval, boundaries included.

Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42
  • This is matching `bijk` but I don't think it should. – Toto Jan 10 '18 at 16:28
  • `b` is between `a` and `g` and between `b` and `z`, so yeah it matches both expressions that requires at least one letter in their interval, doesn't it? – Adrien Brunelat Jan 10 '18 at 16:32
  • @AdrienBrunelat I think the OP wants it anchored, something like: `\b(?=[a-g]+\b)(?=[b-z]+\b)[a-z]+\b` – ctwheels Jan 10 '18 at 16:34
  • @AdrienBrunelat it doesn't match `bijk` with my pattern above using word boundaries: see [here](https://regex101.com/r/1suJUG/1) – ctwheels Jan 10 '18 at 16:40