Lua - 计算字符串中多次出现的次数

问题描述 投票:0回答:1

我需要计算一个字符串中包含多少次出现,但检查多个字符,以下一个(GSM 3.38 扩展字符):

€
[
\
]
^
{
|
}
~

例如给定字符串:

abc€|€]/{def
我需要的数字是6

我使用了一个字符:

local _, c = addr:gsub("€","")

因此 c = 2

而且效果很完美。有人可以让我实现字符串中多次出现的计数吗?

lua
1个回答
0
投票

local _, c = addr:gsub("€","")
不会给出
c = 2
它给出
c = 6
因为
是三个字节宽,Lua 将其视为 3 个字符的字符串。

要获得您所描述的字符的准确计数,您可以执行 2 个单独的

gsub
,其中有 2 种不同模式,一种用于 3 个字节的字符,一种用于单字节:

local str = "abc€|€]/{def"  
local tripleByteCharPattern = "[€]"
local singleByteCharpattern = "[%[%]/^{|}~]"  
local count = select(2, str:gsub(singleBytepattern, ""))  
count = count + select(2, str:gsub(tripleBytePattern, "")) / 3
  
print(count)

此方法需要注意的一件事是,如果可能存在其他类型的多字节宽度字符,您最终可能会在多字节字符内识别出单字节字符之一,解决此问题的方法通常需要识别多字节的开头角色。

© www.soinside.com 2019 - 2024. All rights reserved.