2

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.

3
  • You're matching a substring safari which is not equal to chrome. (Not very meaningful if I understand it correctly.)
    – pimvdb
    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
    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
    Jun 19, 2012 at 21:00

1 Answer 1

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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.