问题
I am using the following regex expression to find SQL parameters, but it is not working under some circumstances.
\@([^=<>\s]+)((?=\s)|$)
If I use this SQL query,
select count(1) from (select * from tblEmailList109 where firstname='@FirstName') t
the value returned is:
@Firstname')
How can I modify the regex to stop stop but do not include a single quote, a space, or the end of the string?
My intention is the replace the parameter before passing it to the SQL server. I know having the single quotes in a normal stored procedure with parameters is not required, but in my case, when I do the replacement, the quotes are needed for string literals when sending to the SQL server.
Thanks
回答1:
If you add an escaped apostrophe to the list of ignores, it works for your test case.
\@([^=<>\s\']+)
回答2:
Based heavily on research by Hunter McMillen, the following looks to fulfil all criteria:
\@([\w.$]+|"[^"]+"|'[^']+')
Working example
Your regex was capturing the trailing ')
because both of those characters are included in your character class [^=<>\s]
I'd also like to point out that the second half of your regex does nothing at all
(|(?=\s)|$)
^^
You have 3 alternatives (in the format (a|b|c)
) to match here:
The middle one (?=\s)
matches where the next character is whitespace, $
matches end of input, but the first alternative (marked with ^^
) says match on nothing. So the alternation will always match because nothing will match between every character.
回答3:
Not sure what SQL you are using, but from the MySQL documentation:
User variables are written as @var_name, where the variable name var_name consists of alphanumeric characters, “.”, “_”, and “$”. A user variable name can contain other characters if you quote it as a string or identifier (for example, @'my-var', @"my-var", or @
my-var
).
So there two possible things to check for:
- Only alphanumeric, underscore, period and dollar sign:
\@[\w\.\$]+
- Anything that is quoted: \@["'`].*["'`]
The second check will return some false positives since it will match strings that don't start and end in the same quote-type, but it is simpler and your SQL editor will complain about mismatching quote-types anyway.
回答4:
I would use the regex
@(?:[\w#_$]{1,128}|(?:(\[)|").{1,128}?(?(1)]|"))
It will find an @
followed by either of these:
- Up to 128
#
,_
,$
, and alphanumeric characters. - Up to 128 characters contained within the delimiters
[]
or""
.
You can find an full explanation and demonstration here: http://regex101.com/r/nY1pR0
来源:https://stackoverflow.com/questions/21286674/using-regex-to-find-sql-parameters-in-a-string