![]() ![]() > = string.match( "foo: 123 bar: 456", '(%a+):%s*(%d+)%s+(%a+):%s*(%d+)') - %a: letter %s: whitespaceĮach capture is returned as a separate result, so this is useful for splitting out values What if you want to get certain pieces out of a string of text? This can be done by wrapping parts of a pattern in ( ), and the contents of each of these captures will be returned from string.match. The solution is to prepend them with a % character: They're not just for use with -, you can just prepend the pattern with ^ to make it match at the start, append $ to make it match at the end, and wrap it in both (like the example above) to make it match the whole string.įinally, you might be thinking how to match all these special characters literally. Here we also introduced ^ and $, which match the start and end of the string. > = string.match( "abc", '^.-b') - the ^ matches the start of the string > = string.match( "abc", 'a.-$') - the $ matches the end of the string When using -, you need to remember to "anchor" it from both sides, otherwise it will match nothing (since it tries to match as little as possible): > = string.match( "one |two| three |four| five", '|*|') - another solution can be to not let the contents match the delimiter > = string.match( "one || three", '|.+|')Ī common mistake with + and * is not realizing that they match as much as possible, which may not be the desired result. > = string.match( "this is some text with a number 12345 in it", '%d+') Note how it's used with a class, so it can match a sequence of different characters: > = string.match( "example", 'examples?') > = string.match( "examples", 'examples?') We'll start with ?, since it's the simplest: ? Make the previous character (or class) optional.- Match the previous character (or class) zero or more times, as few times as possible. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |