2 Answers2

1

You can use lookahead:

  • x(?=y) – positive lookahead (matches 'x' when it's followed by 'y')
  • x(?!y) – negative lookahead (matches 'x' when it's not followed by 'y')

and you can also use lookbehinds:

  • (?<=y)x – positive lookbehinds (matches 'x' when it's precede by 'y')
  • (?<!y)x – negative lookbehinds (matches 'x' when it's not precede by 'y')

These are examples for your need, if you have text with many lines, use this:

(?<=asad=).*?(?=(?:&|\n))

or if you have an array with multiple strings use that

(?<=asad=).*?(?=(?:&|$))

Example on https://regex101.com/r/8LvPtZ/1

Chris
  • 1,253
  • 8
  • 13
0

You want non-greedy matching, and probably want to match either a & or the end of the line as a terminator:

/asad=(.*?)(?:&|$)/

This tells the regex engine:

  1. We're looking for the sequence "asad="
  2. Then, capture everything until...
  3. We see either a "&" or the end of the line ($).

If you use greedy matching (.*) then it'll capture everything until it can't match terminators anymore.

With the test string:

https://teststore.com/collections/men/products/mens-sneakers?variant=310637539&asad=204207_e1c1756d5&foo=bar

The greedy match /asad=(.*)(?:&|$)/ would capture "asad=204207_e1c1756d5&foo=bar", because it can keep greedily matching up until the end-of-line ($), whereas the non-greedy match /asad=(.*)(?:&|$)/ captures just what you want.

Chris Heald
  • 56,837
  • 7
  • 110
  • 130
  • thanks @chris-heald can you share a regex101 example? I am not getting the extracted strings when I try to test: [RegEx 101](https://regex101.com/r/iNLbO5/1/) – Mike Aug 17 '20 at 17:54
  • Your test strings there include the delimiter `avad`, not `asad`. Adjust your test strings or the matcher accordingly. – Chris Heald Aug 17 '20 at 17:55