3

I want to replace any word, character, digit or symbol (except ; , .) followed by the string "some-word\" in Lua. More like a '*' option in regex. Is there any thing similar to '*' in Lua?

Example:

some-word\\test -> some-word\\###

some-word\\b*ax#@$6; -> some-word\\###;

some-word\\?foo,> -> some-word\\###,

The code I'm using:

d = "some-word" 
p = (tostring(d).."\\[.%c%w%p^%;^%,^%.]+") 
c = "###" 
s = "testing some-word\\test-2 later some-word\\&^*; some-word\\set_34$ " 
print(p) 
res = (string.gsub(s,p,c)) print(res)
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Namitha
  • 355
  • 1
  • 6
  • 17
  • This is the code I am using as of now, but it will replace all symbols, how to exclusively say don't replace ; or , or . `d = "some-word" p = (tostring(d).."\\[.%c%w%p^%;^%,^%.]+") c = "###" s = "testing some-word\\test-2 later some-word\\&^*; some-word\\set_34$ " print(p) res = (string.gsub(s,p,c)) print(res)` – Namitha Mar 26 '15 at 04:37
  • 1
    Please move your comment to your question. – Nic Mar 26 '15 at 04:42

1 Answers1

2

(some%-word)\[^;,.%s]* works, note that:

  • - is a magic character in Lua patterns, it needs to be escaped.
  • some%-word is surrounded by (), so that it's captured with %1.
  • In character class, ^ is used in the beginning to indicate complement of the following.

Test:

d = "some%-word" 
p = "(" .. d .. ")" .. "\\[^;,.%s]*"
c = "%1###" 
s = "testing some-word\\test-2 later some-word\\&^*; some-word\\set_34$ " 
print(p) 
res = string.gsub(s,p,c)
print(res)

Output:

(some%-word)\[^;,.%s]*
testing some-word### later some-word###; some-word###
Yu Hao
  • 119,891
  • 44
  • 235
  • 294