Salam.MSaif
Salam.MSaif

Reputation: 219

Regex stop at the first double quote

This is my string '<input type="hidden" name="mode" value="<?=$modeValue?>"/>'

I am trying to take 1) name="mode" and 2) value="<?=$modeValue?>" from it.

I ran two regex to find it which is /name\s*=\s*['\"].*['\"]/ for name="mode" and /value\s*=\s*['\"].*['\"]/ for value="<?=$modeValue?>"

But I fail to get name="mode" on the first regex. Instead I get name="mode" value="$modeValue".

However I succeeded in getting value="<?=$modeValue?>"

What is wrong with my regex for name="mode"? My observation, I think I have to make the regex stops at the first " it encounters. Anyone know how to do this. I am running out of time...

Upvotes: 2

Views: 1238

Answers (2)

Code Maniac
Code Maniac

Reputation: 37775

A little change and your regex is good to go.

name\s*=\s*['\"].*?['\"]
                  ^

Why your regex was not working the way you wanted. So by nature quantifiers are greedy in nature so . will try to match as many characters as it can.

So by adding ? we make it lazy which means it will now try to match as less character as it can.

Demo

In case you want to join both of regex together.

(name=\".*?\")\s*(value=\".*?\")|(value=\".*?\")\s*(name=\".*?\")

Demo2

Upvotes: 3

Sufiyan Ghori
Sufiyan Ghori

Reputation: 18763

You can create capturing groups to match both,

(name=\".*?\")\s*(value=\".*?\")

Demo:

https://regex101.com/r/z9dDE2/1

Upvotes: 0

Related Questions