简体   繁体   English

如何使用 sql 样式转义正则表达式匹配字符串?

[英]how to regex match string escaped with sql style?

examples:例子:

"""Romeo and Juliet"""
'another string that is quoted with '' single quotes'

the problem is that the string can have characters used for db escaping even in it's beginning and end, so regex should look if given char is used in sequence of odd length that is 1,3,5... at the end of matched string问题是字符串可以包含用于 db escaping 的字符,即使在它的开头和结尾,所以正则表达式应该查看给定的字符是否以奇数长度的顺序使用,即 1,3,5... 在匹配字符串的末尾

Try this regex: '(?:[^']|'')*' for single quotes.试试这个正则表达式: '(?:[^']|'')*'用于单引号。 The same for double quotes, ie full regex:双引号也一样,即完整的正则表达式:

'(?:[^']|'')*'|"(?:[^"]|"")*"

In string hello 'my ''beautiful''' 'world'! """Romeo and Juliet"""在字符串中hello 'my ''beautiful''' 'world'! """Romeo and Juliet""" hello 'my ''beautiful''' 'world'! """Romeo and Juliet""" it will find: hello 'my ''beautiful''' 'world'! """Romeo and Juliet"""它将找到:

  1. 'my ''beautiful'''
  2. 'world'
  3. """Romeo and Juliet"""

Where your string includes (or might include) characters that cause problems in your sql, you should always escape.如果您的字符串包含(或可能包含)导致 sql 出现问题的字符,则应始终转义。

If you're using PHP with a mysql database, use mysql_real_escape_string($text);如果您将 PHP 与 mysql 数据库一起使用,请使用mysql_real_escape_string($text); ( docs ) 文档

For other databases and languages, you'll have to check for your specific purposes, but there's likely to be an existing method.对于其他数据库和语言,您必须检查您的特定目的,但可能存在现有方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM