Convert PHP RegEx to JavaScript RegEx

心不动则不痛 提交于 2020-01-06 03:42:06

问题


I have a PHP regular expression I'm using to get the YouTube video code out of a URL.

I'd love to match this with a client-side regular expression in JavaScript. Can anyone tell me how to convert the following PHP regex to JavaScript?

preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=embed/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\‌​n]+#", $url, $matches);

Much appreciated, thanks!


回答1:


I think the only problem is to get rid of the lookbehind assertions (?<=...), they are not supported in Javascript.

The advantage of them is, you can use them to ensure that a pattern is before something, but they are NOT included in the match.

So, you need to remove them, means change (?<=v=)[a-zA-Z0-9-]+(?=&) to v=[a-zA-Z0-9-]+(?=&), but now your match starts with "v=".

If you just need to validate and don't need the matched part, then its fine, you are done.

But if you need the part after v= then put instead the needed pattern into a capturing group and continue working with those captured values.

v=([a-zA-Z0-9-]+)(?=&)

You will then find the matched substring in $1 for the first group, $2 for the second, $3 ...




回答2:


you can replace your look behind assertion using this post

Javascript: negative lookbehind equivalent?



来源:https://stackoverflow.com/questions/9309349/convert-php-regex-to-javascript-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!