Regex to match variables only when inside quotes

Viewed 93

I have many sql files. I am trying to locate files that contain a variable (format of @varname) ONLY if they appear within matching single or double quotes. I only care that it exists and is there, I just need to know the files that this occurs in.

I can match all the quoted strings, but can't figure out how to test that even just a single @ char appears within the match

matching single and double quote pairs (["'])(.*?)\1

example file:

...sql statements

select @sql = 'select * from
Users where id = @id '

...more sql statements

Thanks in advance.

EDIT

Here is a better example file, with comments (sql comments) on which statements should match and examples of ones that shouldn't

...sql statements

-- only this quoted string would match
select @sql = "select * from 
    Users where id = @id "

-- other statements that wouldn't match because not in a pair of quotes
if ltrim(isnull(@stat,'')) <> '' and @stat <> '""'
begin
    select @sql = @sql + " and Stat in ("+@stat+")"
end
if isnull(@atype,'') <> '' 
begin
    select @sql = @sql + " and Type in ("+@atype+")"
end

...more sql statements
2 Answers

Using PCRE and to

to test that even just a single @ char appears within the match

You can use an alternation excluding either " or ' and also exclude matching an @ adding it to the negated character class.

To get both values in the same group, you can use a branch reset group.

=\h*(?|"([^"@]*@[^"@]+)"|'([^@']*@[^'@]*)')

The pattern matches:

  • =\h* Match = and optional horizontal whitespace chars
  • (?| Branch reset group
    • "( Match " and start group 1
      • [^"@]*@ Match optional chars other than " or @ and then match @
      • [^"@]+ Match 1+ chars other than " or @
    • )" Close group 1 and atch "
    • | Or
    • '([^@']*@[^'@]*)' The same as previous pattern, this time for '
  • ) Close branch reset group

Regex demo

Related