Question

local querycreate = "create user 'dddqwd123_dwqd'@'localhost'"
local create, usercreate, username, userhost = querycreate:match("^(%w+)%s+(%w+)%s+\'(%w)\'@\'(%w)\'$")
print(string.format("query: %s", querycreate))
print(string.format(" var create = %s \n var usercreate = %s \n var username = %s \n var userhost = %s", create, usercreate, username, userhost))

query: create user 'dddqwd123_dwqd'@'localhost'
var create = nil
var usercreate = nil
var username = nil
var userhost = nil

My regex works fine on http://regexr.com?37voi.

If I change it to ("^(%w+)%s+(%w+)%s+"), it outputs:

var create = create
var usercreate = user
var username = nil
var userhost = nil

If I remove quotes from querycreate by setting it to "create user dddqwd123_dwqd @ localhost" and use ^(%w+)%s+(%w+)%s+(%w+) @ (%w+)$, then the output is normal.

Was it helpful?

Solution

Your initial pattern:

"^(%w+)%s+(%w+)%s+\'(%w)\'@\'(%w)\'$"
  • The last two captures in your pattern lack + specifiers to indicate that they are to read 1 or more characters.
  • _ is not a word character matched by %w. You will need a character class including _ everywhere you would need to match it.
  • The escaping of ' within a "-quoted string is unnecessary.

With some improvement:

"^(%w+)%s+(%w+)%s+'([%w_]+)'@'([%w_]+)'$"

Alternatively: If you wanted to match anything within a set of quotes ', you could match against its inverse class:

"^(%w+)%s+(%w+)%s+'([^']*)'@'([^']*)'$"

([^']*) will capture anything (including nothing) that isn't ', until the end of the string or a ' is found.

OTHER TIPS

You are missing the + on the parts of the pattern that match the user and domain.

You have "^(%w+)%s+(%w+)%s+\'(%w)\'@\'(%w)\'$"

You need "^(%w+)%s+(%w+)%s+'([%w_]+)'@'([%w_]+)'$" (removed unnecessary single quote escaping and to incorporate @RyanStein's comment about _).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top