Lua string functions
Lua string functions

These are the functions in the "string" table.

Indices, where used, start at 1 for the first character (not zero). Negative numbers count from the right, so -1 is the last character, -2 the second last, and so on.

All strings have a metatable added to them by Lua with an __index entry pointing to the string table. What this means is that you can write string function calls in two ways:


s = "hello, world"
string.len (s) --> 12
s:len ()       --> 12


The second version is shorter as the word "string" is implied. Note the colon after the s, not a dot.





string.byte (s, n)

Returns the ASCII code for the nth character of the string s. The inverse operation is carried out by string.char.
Default for n is 1.


print (string.byte ("ABC")) --> 65 (A is 65 in ASCII)
print (string.byte ("ABC", 2)) --> 66 (B is 66)



string.char (n1, n2, n3, ...)

Receives 0 or more numbers and converts them to the corresponding characters. The inverse operation is carried out by string.byte.


print (string.char (65, 66)) --> AB



string.dump (f)

Converts a function f into binary representation, which can be subsequently processed by loadstring to retrieve the function. The function must be a Lua function without upvalues.


function f () print "hello, world" end
s = string.dump (f)
assert (loadstring (s)) () --> hello, world



string.find (str, pattern, index, plain)

Find the first match of the regular expression "pattern" in "str", starting at position "index".
If found, returns the start and end position, and any captures as additional results.
If not found, returns nil.
If "plain" is true, the search string is plain text, not a regular expression.

Also see string.match which operates in a similar way, but does not return the start and end positions.



Patterns

The standard patterns you can search for are:


 . --- (a dot) represents all characters. 
%a --- all letters. 
%c --- all control characters. 
%d --- all digits. 
%l --- all lowercase letters. 
%p --- all punctuation characters. 
%s --- all space characters. 
%u --- all uppercase letters. 
%w --- all alphanumeric characters. 
%x --- all hexadecimal digits. 
%z --- the character with representation 0. 
%% --- a single '%' character.
%1 --- captured pattern 1.
%2 --- captured pattern 2 (and so on).
%f[s]  transition from not in set 's' to in set 's'.
%b()   balanced pair ( ... ) 


Important - the uppercase versions of the above represent the complement of the class. eg. %U represents everything except uppercase letters, %D represents everything except digits.

There are some "magic characters" (such as %) that have special meanings. These are:


^ $ ( ) % . [ ] * + - ? 


If you want to use those in a pattern (as themselves) you must precede them by a % symbol.

eg. %% would match a single %

You can build your own pattern classes by using square brackets, eg.


[abc] ---> matches a, b or c
[a-z] ---> matches lowercase letters (same as %l)
[^abc] ---> matches anything except a, b or c
[%a%d] ---> matches all letters and digits
[%a%d_] ---> matches all letters, digits and underscore
[%[%]] ---> matches square brackets (had to escape them with %)


The repetition characters are:


+  ---> 1 or more repetitions (greedy)
*  ---> 0 or more repetitions (greedy)
-  ---> 0 or more repetitions (non greedy)
?  ---> 0 or 1 repetition only


The standard "anchor" characters apply:


^  ---> anchor to start of subject string
$  ---> anchor to end of subject string


You can also use round brackets to specify "captures":


You see (.*) here


Here, whatever matches (.*) becomes the first pattern.

You can also refer to matched substrings (captures) later on in an expression:


print (string.find ("You see dogs and dogs", "You see (.*) and %1")) --> 1 21 dogs
print (string.find ("You see dogs and cats", "You see (.*) and %1")) --> nil


This example shows how you can look for a repetition of a word matched earlier, whatever that word was ("dogs" in this case).

As a special case, an empty capture string returns as the captured pattern, the position of itself in the string. eg.


print (string.find ("You see dogs and cats", "You .* ()dogs .*")) --> 1 21 9


What this is saying is that the word "dogs" starts at column 9.

Finally you can look for nested "balanced" things (such as parentheses) by using %b, like this:


print (string.find ("I see a (big fish (swimming) in the pond) here",
       "%b()"))  --> 9 41


After %b you put 2 characters, which indicate the start and end of the balanced pair. If it finds a nested version it keeps processing until we are back at the top level. In this case the matching string was "(big fish (swimming) in the pond)".




Examples of string.find:


print (string.find ("the quick brown fox", "quick")) --> 5 9
print (string.find ("the quick brown fox", "(%a+)")) --> 1 3 the
print (string.find ("the quick brown fox", "(%a+)", 10)) --> 11 15 brown
print (string.find ("the quick brown fox", "fruit")) --> nil



string.format (fstr, v1, v2, v3, ...)

Formats the supplied values (v1, v2 etc.) using format string 'fstr', similar to the C function printf.

It is an error to supply too few variables for the format string.

The format string comprises literal text, and directives starting with %. Each directive controls the format of the next argument. Directives can include flags, width and precision controls.

Directives can be:


  • %c - convert a number to a single character (like string.char)

    
    string.format ("%c", 65) --> A
    


  • %d and %i - output as an integer number

    
    string.format ("%i", 123.456) --> 123
    


  • %o - convert to octal

    
    string.format ("%o", "16") --> 20
    


  • %u - convert to an unsigned number

    Negative numbers will be converted to 4294967296 (2^32) minus the number.

    
    string.format ("%u", "1234.566") --> 1234
    string.format ("%u", "-1234")    --> 4294966062
    


  • %x - hex (lower-case)

    
    string.format ("%x", "86543") --> 1520f
    


  • %X - hex (upper-case)

    
    string.format ("%X", "86543")--> 1520F
    


  • %e - scientific notation, "e" in lower case:

    
    string.format ("%e", "15") --> 1.500000e+001
    


  • %E - scientific notation, "E" in upper case:

    
    string.format ("%E", "15") --> 1.500000E+001
    


  • %f - floating point, default to 6 decimal places:

    
    string.format ("%f", "15.656e4") --> 156560.000000
    


  • %g - Signed value printed in %f or %e format, whichever is more compact for the given value.

    
    string.format ("%g", "15.656") --> 15.656
    


  • %G - Same as %g except that an upper-case E is used where appropriate.

    
    string.format ("%G", "15.656e42") --> 1.5656E+043
    



  • %q - formats a string in such a way Lua can read it back in. Basically this means it puts a backslash in front of the quote character, backslash itself, newline, and the nul character. The string itself is surrounded by quotes.

  • %s - output a string

  • %% - output a single % character



You can optionally supply 'flags width.precision' arguments before the letter.

Flags can be:


  • - : left align result inside field
  • + : always prefix with a sign, using + if field positive
  • 0 : left-fill with zeroes rather than spaces
  • (space) : If positive, put a space where the + would have been
  • # : For octal conversion (o), prefixes the number with 0
    For hex conversion (x), prefixes the number with 0x
    For hex conversion (X), prefixes the number with 0X
    For e, E and f formats, always show the decimal point.
    For g and G format, always show the decimal point, and do not truncate trailing zeroes


Width is the width of the returned field. If the converted number/string is wider than the width it is not truncated.

You cannot use "*" as the width (as you can for printf). If you want variable-size strings you can simulate that by modifying the format string on-the-fly.

eg. instead of %*g, use "%" .. width .. "g"

Precision is the number of decimal places to show for floating-point numbers.


string.format ("%15.1f", "15.656")   --> '           15.7'
string.format ("%15.8f", "15.656")   --> '    15.65600000'
string.format ("%-15.1f", "15.656")  --> '15.7           '
string.format ("%015.1f", "15.656")  --> '0000000000015.7'
string.format ("%+015.1f", "15.656") --> '+000000000015.7
string.format ("%5s", "hi")          --> '   hi'
string.format ("%5-s", "hi")         --> 'hi   '



string.gfind (str, pattern)

This function is now called string.gmatch. Calling string.gfind raises an error.


string.gmatch (str, pattern)

Returns an iterator function for returning the next capture from a pattern over a string. If there is no capture, the whole match is produced.


for w in string.gmatch ("nick takes a stroll", "%a+") do
  print (w)
end -- for

--> 

nick
takes
a
stroll




string.gsub (str, pattern, replacement, n)

Returns a copy of str with matches to 'pattern' replaced by 'replacement', for a maximum of n times.
As a second result it returns the number of matches made.

'replacement' can be a string in which case it simply replaces the matching pattern. However %1 through to %9 in the replacement pattern can refer to captured strings in the source pattern. %% becomes %.

If 'replacement' is a function it is called for each match with the matching string as an argument. It should return a string which is the string to replace it with. If it returns nil the original string is retained.

If 'replacement' is a table then the matching string is looked up in the table for each match, and if found, the replacement is substituted.


string.gsub ("nick eats fish", "fish", "chips") --> nick eats chips

-- example of using a function as the replacement

replacements = { 
   ["nice"] = "windy",
   ["walk"] = "stroll",
   }
   
s = "a nice long walk"

result = string.gsub (s, "%a+", 
  function (str)
  return replacements [str]
  end
  )

print (result) --> a windy long stroll

-- An alternative way of doing a table replacement using the above table:

result = string.gsub (s, "%a+", replacements)

print (result) --> a windy long stroll

-- You can call inbuilt functions too:

s = "a nice long walk"

result = string.gsub (s, "%f[%a]%a%a", string.upper)

print (result) --> a NIce LOng WAlk




string.len (str)

Returns the length of the string, including any imbedded zero (0x00) bytes.


string.len ("hi there") --> 8


You can also use #string to find its length.


#"hi there" --> 8



string.lower (str)

Returns the string converted to lower-case.


string.lower ("ABCdef") --> abcdef



string.match (str, pattern, index)

Find the first match of the regular expression "pattern" in "str", starting at position "index".
If found, returns any captures in the pattern. If no captures were specified the entire matching string is returned.
If not found, returns nil.

This is similar to string.find, except that the starting and ending index are not returned.


print (string.match ("You see dogs and cats", "s..")) --> see


string.rep (str, n)

Returns a string which is n copies of the source string concatenated together.


string.rep ("moo", 4) --> moomoomoomoo


string.reverse (str)

Returns a string that is the string str reversed.


string.reverse ("nickgammon") --> nommagkcin



string.sub (str, start, end)

Returns a substring of the string, starting at index 'start' and ending at index 'end'. Both may be negative to indicate counting from the right. The end point is optional and defaults to -1, which is the entire rest of the string.


string.sub ("ABCDEF", 2, 3)  --> BC
string.sub ("ABCDEF", 3)     --> CDEF
string.sub ("ABCDEF", -1)    --> F



string.upper (str)

Returns the string converted to upper-case.


string.upper ("ABCdef") --> ABCDEF



See Also ...

Topics

DOC_lua_base Lua base functions
DOC_lua_coroutines Lua coroutine functions
DOC_lua_debug Lua debug functions
DOC_lua_io Lua io functions
DOC_lua_math Lua math functions
DOC_lua_os Lua os functions
DOC_lua_package Lua package functions
DOC_lua Lua script extensions
DOC_lua_tables Lua table functions
DOC_regexp Regular Expressions

(Help topic: general=lua_string)

DOC_contents Documentation contents page