1

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...

Salam.MSaif
  • 209
  • 3
  • 10

2 Answers2

2

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

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • This is working the way I want. So the theory is, by making it lazy, it finds the .* and then it finds ['\"] and then, coz it being lazy, it wont go and search anymore? right? – Salam.MSaif Dec 05 '18 at 04:44
  • @Salam.MSaif yeah.you can read here more about it https://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions – Code Maniac Dec 05 '18 at 04:47
  • @Salam.MSaif, this is rather complex for no reason. my answer is much more cleaner and straight forward, which is also what this answer has copied as the 2nd case. – Sufiyan Ghori Dec 05 '18 at 04:51
  • @SufiyanGhori `(name=\".*?\")|(value=\".*?\")` well in your case it will match `` this too. i don't think op wants this. ? – Code Maniac Dec 05 '18 at 04:55
0

You can create capturing groups to match both,

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

Demo:

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

Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110