Regexp to validate URL in MySQL

雨燕双飞 提交于 2019-12-29 09:02:45

问题


I have tried several regex patterns (designed for use with PHP because I couldn't find any for MySQL) for URL validation, but none of them are working. Probably MySQL has a slightly different syntax.

I've also tried to come up with one, but no success.

So does anyone know a fairly good regex to use with MySQL for URL validation?


回答1:


According to article 11.5.2. Regular Expressions in MySQL's documentation, you can perform selections with a regular expression with the following syntax

SELECT field FROM table WHERE field REGEX pattern

In order to match simple URLS, you may use

SELECT field FROM table
 WHERE field REGEXP "^(https?://|www\\.)[\.A-Za-z0-9\-]+\\.[a-zA-Z]{2,4}"

This will match most urls like

  • www.google.il
  • http://google.com/
  • http://ww.google.net/
  • www.google.com/index.php?test=data
  • https://yahoo.dk/as
  • http://goo.gle.com/
  • http://wt.a.x24-s.org/ye/
  • www.website.info

But not

  • htp://google.com
  • ww.google.com/
  • www-google.com
  • http://google.c
  • http://goo#.com
  • httpf://google.com



回答2:


Although the answer KBA posted works, there are some inconstancies with the escaping.

The proper syntax should be, this syntax works in MySQL as well as in PHP for example.

SELECT field FROM table
 WHERE field REGEXP "^(https?:\/\/|www\.)[\.A-Za-z0-9\-]+\.[a-zA-Z]{2,4}"

The above code will only match if the content of 'field' starts with a URL. If you would like to match all rows where the field contains a url (so for example surrounded by other text / content) just simply use:

SELECT field FROM table
 WHERE field REGEXP "(https?:\/\/|www\.)[\.A-Za-z0-9\-]+\.[a-zA-Z]{2,4}"


来源:https://stackoverflow.com/questions/9033018/regexp-to-validate-url-in-mysql

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