Wasim A. Wasim A. - 10 days ago 8
Javascript Question

Regex Match based on two strings using AND

I want to extract commands from a string. The commands I need contain specific ids 124 and 123 and also specific flag od and xy. So I want to extract all those commands which

contained my ids [123|124]
and
my flags[od|xy]
only.

String:
Z124xy54;Z123od33;Z123od343;Z251od541;Z251ab541;


Regex:
Z[^;]*?(od|xy)[^;]*?;


Required Output:
[Z124xy54; Z123od33; Z123od343;]


But Current Output :
[Z123xy54; Z123od33; Z123od343; Z251od541;]


I know why its happening that way but don't know how to solve this. Any one could help please

Another Sample:

Z124xy54;Z123od33;Z123od343;Z251od541;Z251ab541;Z123od343;
Z124xy54;Z123od33;Z123od343;Z251od541;Z251ab541;Z123od343X

Answer

Use :

(Z(?:123|124)(?:xy|od).*?(:?;|$))
  1. Start with Z => (Z)
  2. Match 123 or 124 without capturing group => (?:123|124)
  3. Match zy or od without capturing group => (?:xy|od)
  4. Match anything except newline untill first ; or end of string found without capturing group => (:?;|$)

Working Demo : https://regex101.com/r/AugDZT/2