gpt4 book ai didi

正则表达式用两个连续的管道 || 分割字符串

转载 作者:行者123 更新时间:2023-12-02 17:58:33 25 4
gpt4 key购买 nike

我想用两个管道(||)正则表达式分割下面的字符串。

输入字符串

value1=data1||value2=da|ta2||value3=test&user01|

预期输出

value1=data1
value2=da|ta2
value3=test&user01|

我尝试了 ([^||]+) 但它考虑单管道 |还要 split 。

试试我的例子 - Regex

value2 有单个管道,不应被视为匹配。

我正在使用lua脚本,例如

for pair in string.gmatch(params, "([^||]+)") do 
print(pair)
end

最佳答案

您可以显式查找每个 ||

$ cat foo.lua
s = 'value1=data1||value2=da|ta2||value3=test&user01|'

offset = 1
for idx in string.gmatch(s, '()||') do
print(string.sub(s, offset, idx - 1) )
offset = idx + 2
end
-- Deal with the part after the right-most `||`.
-- Must +1 or it'll fail to handle s like "a=b||".
if offset <= #s + 1 then
print(string.sub(s, offset) )
end
$ lua foo.lua
value1=data1
value2=da|ta2
value3=test&user01|

关于()||请参阅Lua关于Patterns的文档(Lua没有正则表达式支持) -

  • Captures:

    A pattern can contain sub-patterns enclosed in parentheses; they describe captures. When a match succeeds, the substrings of the subject string that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern "(a*(.)%w(%s*))", the part of the string matching "a*(.)%w(%s*)" is stored as the first capture, and therefore has number 1; the character matching "." is captured with number 2, and the part matching "%s*" has number 3.

    As a special case, the capture () captures the current string position (a number). For instance, if we apply the pattern "()aa()" on the string "flaaap", there will be two captures: 3 and 5.

关于正则表达式用两个连续的管道 || 分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75027692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com