Forum

> > CS2D > Scripts > Check if a string contains \
Forums overviewCS2D overview Scripts overviewLog in to reply

English Check if a string contains \

6 replies
To the start Previous 1 Next To the start

old Check if a string contains \

Mami Tomoe
User Off Offline

Quote
Hi I need a function to check if a string contains \ inside it and if it does then it will return the string without it (even if it contains it many many times)
Also if possible I need to be able to add more things for it to remove like a table:

toRemove = {"\","#"}


Please help thanks

old Re: Check if a string contains \

Mami Tomoe
User Off Offline

Quote
Yes but for example I have a string like this:

example = "\#hi friends"


And I call it like that:

example_fixed = fixString(example)


Then it will check if the string contains anything inside the table

toRemove = {"\","#"}


and if it does then it will return the string without them like that:

example_fixed = "hi friends"

old Re: Check if a string contains \

Hajt
User Off Offline

Quote
1
2
3
4
5
6
7
8
9
10
toRemove = {"\\","#"}

function escape_string(text)
	for i = 1, #toRemove do
		text = string.gsub(text, toRemove[i], "")
	end
	return text
end

print(escape_string("\#hi friends"))

old Re: Check if a string contains \

VADemon
User Off Offline

Quote
https://www.lua.org/manual/5.3/manual.html#pdf-string.format
String.format %q will safely escape all Lua sequences, so it can be e.g. read back from a file:
1
print(string.format("%q", "\\#"))
Lua demo: https://www.lua.org/cgi-bin/demo

Replace any character:
1
2
3
badchars = "Aabc\\#,%" -- case-sensitive
badchars = "[".. badchars:gsub("[%(%)%.%%%+%-%*%?%[%^%$%]]", "%%%1") .."]" -- escape Lua regex and make it a pattern
print(string.gsub("Awful string by hacker omg\\thats#illeg'al!", badchars, "@"))
There's no need to run string.sub in a loop like @user Hajt did for every character in the table, because string.gsub accepts a regex pattern.

Gosh, I look like a magician now with that 2nd line

string.gsub(text, pattern, replace-with[, n])
edited 1×, last 08.06.17 01:48:42 am
To the start Previous 1 Next To the start
Log in to reply Scripts overviewCS2D overviewForums overview