'How to match the start or end of a string with string.match in 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?

lua


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1