How to find matches in regex only if they are between particular strings?

Viewed 102

I'm trying to find multiple matches in a specific position in text.

For example, in the following text, I want to find all a=.*; between abcd and xyz

abcd
a=1;
some text
a=2; some text
b=3;
a=4;
xyz
a=5;
a=6;

So it should only match:

 a=1;   
 a=2;
 a=4;

and don't match:

a=5;
a=6;

So far I tried the following regex:

(?<=abcd\n)(.*)(?=\nxyz) 

which returns the string between 'abcd' and 'xyz' ,but I don't succeed to match all a=.*; inside

1 Answers

Use

(?<=abcd[\s\S]*)a=.*;(?=[\s\S]*xyz)

See JS regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    abcd                     'abcd'
--------------------------------------------------------------------------------
    [\s\S]*                  any character of: whitespace (\n, \r,
                             \t, \f, and " "), non-whitespace (all
                             but \n, \r, \t, \f, and " ") (0 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  a=                       'a='
--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  ;                        ';'
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    [\s\S]*                  any character of: whitespace (\n, \r,
                             \t, \f, and " "), non-whitespace (all
                             but \n, \r, \t, \f, and " ") (0 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    xyz                      'xyz'
--------------------------------------------------------------------------------
  )                        end of look-ahead
Related