Namitha
Namitha

Reputation: 365

Trying to match a string in the format of domain\username using Lua and then mask the pattern with '#'

I am trying to match a string in the format of domain\username using Lua and then mask the pattern with #.

So if the input is sample.com\admin; the output should be ######.###\#####;. The string can end with either a ;, ,, . or whitespace.

More examples:

sample.net\user1,hello   ->   ######.###\#####,hello
test.org\testuser. Next  ->   ####.###\########. Next

I tried ([a-zA-Z][a-zA-Z0-9.-]+)\.?([a-zA-Z0-9]+)\\([a-zA-Z0-9 ]+)\b which works perfectly with http://regexr.com/. But with Lua demo it doesn't. What is wrong with the pattern?

Below is the code I used to check in Lua:

test_text="I have the 123 name as domain.com\admin as 172.19.202.52 the credentials"
pattern="([a-zA-Z][a-zA-Z0-9.-]+).?([a-zA-Z0-9]+)\\([a-zA-Z0-9 ]+)\b"
res=string.match(test_text,pattern)
print (res)

It is printing nil.

Upvotes: 1

Views: 1304

Answers (2)

tonypdmtr
tonypdmtr

Reputation: 3235

Like already mentioned pure Lua does not have regex, only patterns. Your regex however can be matched with the following code and pattern:

--[[
sample.net\user1,hello   ->   ######.###\#####,hello
test.org\testuser. Next  ->   ####.###\########. Next
]]

s1 = [[sample.net\user1,hello]]
s2 = [[test.org\testuser. Next]]
s3 = [[abc.domain.org\user1]]

function mask_domain(s)
  s = s:gsub('(%a[%a%d%.%-]-)%.?([%a%d]+)\\([%a%d]+)([%;%,%.%s]?)',
      function(a,b,c,d)
        return ('#'):rep(#a)..'.'..('#'):rep(#b)..'\\'..('#'):rep(#c)..d
      end)
  return s
end

print(s1,'=>',mask_domain(s1))
print(s2,'=>',mask_domain(s2))
print(s3,'=>',mask_domain(s3))

The last example does not end with ; , . or whitespace. If it must follow this, then simply remove the final ? from pattern.

UPDATE: If in the domain (e.g. abc.domain.org) you need to also reveal any dots before that last one you can replace the above function with this one:

function mask_domain(s)
  s = s:gsub('(%a[%a%d%.%-]-)%.?([%a%d]+)\\([%a%d]+)([%;%,%.%s]?)',
      function(a,b,c,d)
        a = a:gsub('[^%.]','#')
        return a..'.'..('#'):rep(#b)..'\\'..('#'):rep(#c)..d
      end)
  return s
end

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122493

Lua pattern isn't regular expression, that's why your regex doesn't work.

  • \b isn't supported, you can use the more powerful %f frontier pattern if needed.
  • In the string test_text, \ isn't escaped, so it's interpreted as \a.
  • . is a magic character in patterns, it needs to be escaped.

This code isn't exactly equivalent to your pattern, you can tweek it if needed:

test_text = "I have the 123 name as domain.com\\admin as 172.19.202.52 the credentials"
pattern = "(%a%w+)%.?(%w+)\\([%w]+)"
print(string.match(test_text,pattern))

Output: domain com admin


After fixing the pattern, the task of replacing them with # is easy, you might need string.sub or string.gsub.

Upvotes: 3

Related Questions