Utf8.gsub: Difference between revisions
Jump to navigation
Jump to search
m (tweaks) |
(Add warning) |
||
Line 3: | Line 3: | ||
Returns a copy of the original input string with replaced matches from the pattern by the replacement value. | Returns a copy of the original input string with replaced matches from the pattern by the replacement value. | ||
{{Warning|This function may modify your input string even if no changes were made. Try it with runcode: <pre>srun utf8.gsub(utf8.char(66376), "", "") == utf8.char(66376)</pre>}} | |||
==Syntax== | ==Syntax== |
Latest revision as of 03:27, 1 August 2019
Returns a copy of the original input string with replaced matches from the pattern by the replacement value.
Warning: This function may modify your input string even if no changes were made. Try it with runcode: srun utf8.gsub(utf8.char(66376), "", "") == utf8.char(66376) |
Syntax
string utf8.gsub ( string input, string pattern, mixed replace [, int match_limit = utf8.len( input ) ] )
Required Arguments
- input: A string character sequence
- pattern: A string match pattern
- replace: A string literal OR an integer value OR a function (see examples below) OR a table ({ match = replacement })
Optional Arguments
NOTE: When using optional arguments, you might need to supply all arguments before the one you wish to use. For more information on optional arguments, see optional arguments.
- match_limit: An integer to limit the number of substitutions made
Returns
Returns a pair of values, the modified string and the integer number of substitutions made.
Example
Click to collapse [-]
ServerThis example shows how to remove color codes from a string and how to uppercase each single character in a string.
local text= "#ff0000This text is red" local colorless = utf8.gsub( text, "#%x%x%x%x%x%x", "" ) print( colorless ) -- This text is red print( utf8.gsub( "Nice wiki!", ".", utf8.upper ) ) -- NICE WIKI!
Click to collapse [-]
ServerThis example uses a table to replace specific words in the input string by an other value.
local input = "We have nice weather in London" local replacements = { ["weather"] = "food", ["London"] = "Germany" } local output = utf8.gsub( input, "%w+", replacements ) print( output ) -- We have nice food in Germany
Click to collapse [-]
ClientThis example shows a simple bad word filter, which censors the word 'ugly' in the input string.
local input = "You are ugly!" local badwords = { ["ugly"] = true } local output = utf8.gsub( input, "%w+", function (match) local lowerCase = utf8.lower( match ) if badwords[ lowerCase ] then return string.rep( '*', utf8.len( match ) ) end return match end ) outputConsole( output ) -- You are ****!
See Also
Shared
- utf8.byte
- utf8.char
- utf8.charpos
- utf8.escape
- utf8.find
- utf8.fold
- utf8.gmatch
- utf8.gsub
- utf8.insert
- utf8.len
- utf8.lower
- utf8.match
- utf8.ncasecmp
- utf8.next
- utf8.remove
- utf8.reverse
- utf8.sub
- utf8.title
- utf8.upper
- utf8.width
- utf8.widthindex