17

I have the following string:

_name=aVlTcWRjVG1YeDhucWdEbVFrN3pSOHZ5QTRjOEJZZmZUZXNIYW1PV2RGOWYrczBhVWRmdVJTMUxYazVBOE8zQ3JNMmNVKzJLM2JJTzFON3FiLzFHUE0xY0pkdz09LS1jbkkwaWoxUUl3YVhMMkhtZHpaOW13PT0"%"3D--57356371d167f"

I want to match everything between = and the end " (note there are other quotes after this so I can't just select the last ").

I tried using _name=(.*?)" but there are other quotes in the string as well. Is there a way to match the 3rd quote? I tried _name=(.*?)"{3} but the {3} matches for the quotes back to back, i.e. """

You can try it here

2
  • 1
    put " inside the parenthesis. Commented Feb 10, 2015 at 18:09
  • This still only matches up to the first quote
    – Bijan
    Commented Feb 10, 2015 at 18:25

2 Answers 2

22

You can use this regex:

\b_name=(?:[^"]*"){3}

RegEx Demo

RegEx Details:

  • \b_name: Match full word _name:
  • =: Match a =
  • (?:[^"]*"){3}: Match 0 or more non-" characters followed by a ". Repeat this group 3 times.
2
  • This solution even matches _name= along with the required match which we don't want! so shouldn't we just add a bracket around like this: _name=((?:[^"]*"){3}) regex101.com/r/oK0eO2/374 Please tell me if I got this wrong? Commented Jun 21, 2021 at 21:31
  • If you want to capture part after = then _name=((?:[^"]*"){3}) seems correct.
    – anubhava
    Commented Jun 23, 2021 at 6:08
1

If want to match everything between the first and the third(!) double quote (the third isn't necessarily the last, you told), you can use a pattern like this:

$string = '_name=foo"bar"test" more text"';
// This pattern will not include the last " (note the 2, not 3)
$pattern = '/_name=((.*?"){2}.*?)"/';

preg_match($pattern, $string, $m);
echo $m[1];

Output:

foo"bar"test

Original answer:

I'm not sure if I got you correctly, but it sounds like you want to perform a so called greedy match, meaning you want to match the string until the last " regardless whether the string contains multiple "s.

To perform a greedy match, just drop the ?, like this:

_name=(.*)"

You can try it here: https://regex101.com/r/uC5eO9/2

1
  • This is part of a curl request. There are other quotes after this but I am just looking to match the 3rd quote. Your code will match the last one which is not what I want
    – Bijan
    Commented Feb 10, 2015 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.