如何在 Lua 中使用 string.match 匹配字符串的开头或结尾?

我正在使用这个方法来匹配出现在两个单词之间的文本:

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

我该如何在一个字符串开头和一个数字之间,或者一个数字和字符串结尾之间进行匹配?

原文链接 https://stackoverflow.com/questions/10159817

点赞
stackoverflow用户501459
stackoverflow用户501459

如何匹配字符串的开头和数字或数字和字符串的结尾?

使用^将模式锚定到字符串的开头。 使用$将模式锚定到字符串的结尾。

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

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

或者匹配任何数字:

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

第一个模式稍微改动一下,使用非贪婪匹配,它会尽可能匹配尽量少的字符。如果我们使用了.*而不是.-,那么我们匹配到的就是The number 77

2012-04-16 03:21:51