3

I have this regex:

 /.*v\=([\w-]+).*(&autoplay\=1)?/

Which I am trying to match against:

 http://www.youtube.com/watch?v=awmLS6GCJno&width=1000&height=300&autoplay=1

This does not work. (It matches the v=.. but not the autoplay=1)

However, if I change my regex to:

 /.*v\=([\w-]+).*(&autoplay\=1)/

(no ? after autoplay), then it does match both.. (but now a URL without &autoplay won't get matched any more).. which is why I added the ? after that group.. Is that wrong? Is there another way?

Oops about that autofill title, obviously not the issue.

  • The problem is probably not caused by the RegExp. – Rob W Oct 18 '11 at 08:50
  • I tested it with an online regexp tester and it does not match: http://gskinner.com/RegExr/ –  Oct 18 '11 at 08:52
  • I tested your first regex, with the link (both with and without `&autoplay=1`) and it matched both times. Tested this using expresso, and gskinner.com\regexr - therefore I conclude your problem is elsewhere! – Jamiec Oct 18 '11 at 09:05
  • @Jamiec I tested with regexr too, if you test the one with ? at the end, you will note that, whilst you hover over the matched URL, the second submatch is not available. (autoplay=1) is not matched, yet it is in the string.. –  Oct 18 '11 at 09:06

1 Answers1

4

Your RegExp does work, but probably not as intended.

1. /.*v\=([\w-]+).*(&autoplay\=1)?/
2. /.*v\=([\w-]+).*(&autoplay\=1)/

  • The first RegExp has a quantifier ?, which means: "Match none or once".
  • This group is prefixed by .*, which means: "Match anything(except for newlines), as much as possible.
  • Because of the ? quantifier, the RegExp is also valid when &autoplay=1 isn't grouped (it will be matched by.*)

You're probably looking for this RegExp.

/.*v=([\w-]+).*?(&autoplay=1|$)/

  • .*? means: "Match anything(except for newlines), as less as possible to get the RegExp match.
  • (&autoplay=1|$) means: "Match &autoplay=1 or the end of the string ($). If end of the string identifier is omitted, .*? would match NOTHING, because .*? is also valid for an empty string.
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Quick question: If `.*` is greedy, why doesn't that `.*` at the start of the regex simply match any expression? – ankit Oct 18 '11 at 09:16
  • What if &autoplay=1 is not the end of the string? do I just change it to |.*) ? –  Oct 18 '11 at 09:17
  • No, `.*` will also be valid if nothing is matches, causing the RegExp to fail. You can delimit your pattern by characters which won't occur for sure: `(&autoplay=1|[^a-zA-Z0-9&=_-]|$)` will do. – Rob W Oct 18 '11 at 09:23