如何使用整个单词作为分隔符来拆分字符串?

有没有一种方法可以将字符串分割成这样:

"importanttext1已从stackoverflow收集到importanttext2。"

我想获取单词“has”之前的任何内容,只想获取“gathered”之后的一个单词,所以不包括“from stackoverflow。”我想留下包含 importanttext1 importanttext2的2个变量。

点赞
用户1009479
用户1009479
本地的 str 变量中含有文本 "importanttext1 has gathered importanttext2 from stackoverflow."
通过 str:match 方法可以匹配文本中的子字符串。
local s1 = str:match("(.+)has") -- 匹配 "has" 之前的所有字符
local s2 = str:match("gathered%s+(%S+)") -- 匹配 "gathered" 后面的非空白字符
print(s1) -- 输出:importanttext1 
print(s2) -- 输出:importanttext2

需要注意的是,"%s" 可以匹配空白字符,而"%S" 可以匹配非空白字符。
2014-06-25 13:52:55