Lua 正则表达式匹配逗号前的单词

我所需要的文本段始终以“Also there is”开头并以句号结尾。我要定位的是逗号中间的单个名称(例如下面的“randomperson”)。这些名称将始终不同。这会变得棘手,因为存在其他不是单个词“名称”的东西。也许我可以仅在逗号之间匹配所有东西,但只有它是单个单词/名称时,我才能解决这个问题。名称列表可能更长甚至更短,因此表达式必须是动态的,不能仅匹配一定数量的名称。

目标文本:

Also there is a reinforced stone wall, a wooden wall, a stone wall, randomperson, a lumbering earth elemental, randomperson, randomperson, randomperson.

第1组:Also there is (.*).

目标是“is”后面的所有内容,但我需要一些方法来隔离单个单词。

我该如何解决这个问题?

点赞
用户7552
用户7552

你可以这样做:

s = "Also there is a reinforced stone wall, a wooden wall, a stone wall, randomperson, a lumbering earth elemental, randomperson, randomperson, randomperson."
str = s:sub(15,-2)
things = {}
start = 1
while true do
  a, b = str:find("[^,]+", start)
  if not a then break end
  table.insert(things, str:sub(a, b))
  start = b + 3
end
for _,thing in ipairs(things) do print("-> " .. thing) end

输出结果为:

-> a reinforced stone wall
-> a wooden wall
-> a stone wall
-> randomperson
-> a lumbering earth elemental
-> randomperson
-> randomperson
-> randomperson

或者安装一个 luarocks 模块 split,就像这样简单:

split = require("split")
things = split.split(s:sub(15,-2), ", ")

使用 gmatch

for thing in s:sub(14, -2):gmatch("%f[%S][^,]+") do print(thing) end

我在这里使用了一个“前缘”模式来丢弃逗号后面的空格。

2019-05-06 14:47:02
用户1244588
用户1244588

我不完全确定问题的方向,但是问题可能对于正则表达式甚至是Lua模式来说过于复杂。既然我喜欢语法,这里有一些LPeg

local l = require "lpeg";
local V, P, R, S = l.V, l.P, l.R, l.S;
local OUT = function(T, ... ) return function(...) print(T, ...) end end

local g = P{ "S",
    S = 'Also there is ' * V'List' * '.',
    List = V'Item' * (P',' * ' ' * V'Item')^0,
    Item = V'Specific_Noun' + V'Name',
    Name = V'Word'                                                   /OUT'Name',
    Specific_Noun = (P'a' + 'an') * ' ' * (V'Word' * ' ')^0 * V'Noun',
    Noun = V'Word'                                                   /OUT'Noun',
    Word = R('az','AZ')^1,
}

g:match("Also there is a reinforced stone wall, a wooden wall, a stone wall, "..
"randomperson, a lumbering earth elemental, randomperson, randomperson, rando"..
"mperson, Karl, Greta, a mile.")

输出示例:

Noun    wall
Noun    wall
Noun    wall
Name    randomperson
Noun    elemental
Name    randomperson
Name    randomperson
Name    randomperson
Name    Karl
Name    Greta
Noun    mile

这个语法显然只能解析大大简化的列表,但它将匹配您的基本要求,并且很容易扩展。

2019-05-07 23:38:41