admin管理员组

文章数量:1419242

I need to match Safari browsers, but not Chrome browsers using one Regex. I usually don't have a problem with regex, but negative look-aheads are stumping me here.

/(?!chrome)(safari)/i.test("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");

Can't figure out why this is returning true.

I need to match Safari browsers, but not Chrome browsers using one Regex. I usually don't have a problem with regex, but negative look-aheads are stumping me here.

/(?!chrome)(safari)/i.test("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");

Can't figure out why this is returning true.

Share Improve this question edited Aug 29, 2012 at 11:39 tchrist 80.5k31 gold badges131 silver badges184 bronze badges asked Jun 19, 2012 at 20:49 dtbarnedtbarne 8,2305 gold badges46 silver badges49 bronze badges 3
  • You're matching a substring safari which is not equal to chrome. (Not very meaningful if I understand it correctly.) – pimvdb Commented Jun 19, 2012 at 20:53
  • Hmm, I'm probably misinterpreting the use. I'm trying to have the string match safari, but only if the string doesn't match chrome. – dtbarne Commented Jun 19, 2012 at 20:57
  • Negative lookahead: q(?!u) matches a q that is not followed by a u. That won't help here. You actually need a negative lookbehind for this job (string contains Safari that is not preceded by Chrome) but JS does not support negative lookbehind. – Matt Ball Commented Jun 19, 2012 at 21:00
Add a ment  | 

1 Answer 1

Reset to default 5

This will do it

^(?!.*chrome).*(safari)

BTW JavaScript does not support lookbehind but I see no problem with lookahead.

What you are saying with

(?!chrome)(safari)

Is that right before "safari" (zero width so starting with the cursor before s) there cannot be the string "chrome" which doesn't make sense.

本文标签: javascriptRegex Negative Lookahead for Chrome amp SafariStack Overflow