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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With