Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match the start or end of a string with string.match in Lua?

Tags:

lua

I am using this to match the text which appears between two words:

a1 = "apple"
a2 = "bear"
match_pattern = string.format('%s(.*)%s', a1, a2)
str = string.match(str, match_pattern)

How can I make a match between the start of the string and a number or a number and the end of the string?

like image 927
Village Avatar asked Apr 15 '12 05:04

Village


1 Answers

match between the start of the string and a number or a number and the end of the string?

^ at the start of a pattern anchors it to the start of the string. $ at the end of a pattern anchors it to the end of the string.

s = 'The number 777 is in the middle.'

print(s:match('^(.*)777')) --> 'The number '
print(s:match('777(.*)$')) --> ' is in the middle.'

or to match any number:

print(s:match('^(.-)%d+')) --> 'The number '
print(s:match('%d+(.*)$')) --> ' is in the middle.'

The first pattern changes slightly to use a non-greedy match, which will match as few characters as possible. If we'd used .* rather than .-, we would have matched The number 77.

like image 91
Mud Avatar answered Oct 16 '22 18:10

Mud