lua - way to set dynamic pattern matcher -


please question pattern ^u.meta(\.|$) not working expected has expected behavior need.

changes

in pattern ^u.meta(\.|$) or in lua '^u%.meta%f[\0.]' or '^u%.meta%f[%z.]', change need u.meta can user defined variable. , pattern should generic/dynamic match set in variable.

for example:

-- should return 'u.meta', , pattern should match local pattern = 'u.meta' print(string.match("u.meta.admin", '^u%.meta%f[\0.]')) -- u.meta  -- should return 'nil', , pattern should fail local pattern = 'u.meta' print(string.match("u.domain.admin", '^u%.meta%f[\0.]')) -- nil  -- should return 'anything.anything', , pattern should match local pattern = 'anything.anything' print(string.match("anything.anything.something", '^anything%.anything%f[\0.]') -- anything.anything  -- should return nil, , pattern should fail local pattern = 'anything.anything' print(string.match("fake.fake.something", '^anything%.anything%f[\0.]') -- nil 

solution 1

so, thinking interpolation in lua pattern, if possible.

"^#{pattern}%f[\0.]" 

working solution 2

i have made working of method. still have call pattern manually. if can fix pattern itself, great

example:

function pattern_matcher(v, pattern) return string.match(v, pattern) end  print(pattern_matcher("fake.fake.something", '^u%.meta%f[%z.]')) -- nil print(pattern_matcher("u.meta.something", '^u%.meta%f[%z.]')) -- u.meta print(pattern_matcher("u.meta_something", '^u%.meta%f[%z.]')) -- nil print(pattern_matcher("u.meta-something", '^u%.meta%f[%z.]')) -- nil 

if need support user input literal part of regex pattern, need introduce escaping function magic characters escaped %. then, concatenate custom boundaries (^ start of string, , %f[%z.] end of string or dot).

function escape (s)       return string.gsub(s, '[.*+?^$()[%%-]', "%%%0") end function pattern_matcher(v, pattern) return string.match(v, pattern) end  word = "u.meta" print(pattern_matcher("u.meta.something", '^' .. escape(word) .. '%f[%z.]')) -- u.meta 

see this demo

in escape function, first 2 %% in replacement pattern denote 1 %, , %0 backreferences whole match (one of magic characters)


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -