string - Lua模式分离问题

标签 string lua string-matching lua-patterns

我需要一些帮助来创建我的模式。我已经完成了基本部分,但还有一个问题。

假设我有一个字符串如下:

John: I can type in :red:colour! :white:Not in the same :red:wo:green:rd :white:though :(

我有这个代码设置来将颜色与实际值分开:

line = "John: I can type in :red:colour! :white:Not in the same :red:wo:green:rd :white:though :("

for token in string.gmatch(line, "%s?[(%S)]+[^.]?") do
   for startpos, token2, endpos in string.gmatch(token, "()(%b::)()") do
      print(token2)
      token = string.gsub(token, token2, "")
   end
   print(token)
end

将输出:

John: 
I 
can 
type 
in 
:red:
colour! 
:white:
Not 
in 
the 
same 
:red:
:green:
word 
:white:
though 
:(

当我想要它打印出来时:

John: 
I 
can 
type 
in 
:red:
colour! 
:white:
Not 
in 
the 
same 
:red:
wo
:green:
rd 
:white:
though 
:(

如有任何帮助,我们将不胜感激。

最佳答案

以下代码将为您提供 desired output :

for token in line:gmatch( "(%S+)" ) do
  if not token:match( "(:%w-:)([^:]+)" ) then
    print(token)
  else
    for col, w in token:gmatch( "(:%w-:)([^:]+)" ) do
      print( col )
      print( w )
    end
  end
end

不过,对于如下字符串,它会失败:

in the sa:yellow:me:pink:long-Words!

关于string - Lua模式分离问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483230/

相关文章:

c++ - 在 T 不是字符类型的情况下, basic_string<T> 有什么用吗?

java - 使用 char 而不是 String 的要点

c++ - Lua + SWIG 猴子补丁

python - 使用引用号搜索文件

java - 字符串连接转换为 Java 中的 stringbuilder

lua - 分析时,将被调用者时间累积给调用者的正确(或好的)方法是什么?

lua - 克隆 Lua 状态

Java字符串匹配: € symbol is â¬

string - 从一组字符串中找到一个最佳字符串(具有最小长度),使得结果字符串必须包含每个字符串的无规则图

Java:字符串什么时候进入字符串常量池?