我有苹果/香蕉/橘子/樱桃:Z 1234和鳄梨/哈密瓜/西瓜:Y 5678。
如何将苹果/香蕉/橘子和鳄梨/哈密瓜/西瓜的单品搭配起来呢?
如果我放r'(.+?/.+?/.+?):.*,我会得到鳄梨/哈密瓜/西瓜,但我会得到苹果/香蕉/橘子/樱桃(目标应该是苹果/香蕉/橘子)
如果我放r'(.+?/.+?/.+?)/.*,我会得到苹果/香蕉/橘子,但我会得到鳄梨/香瓜/西瓜:Y 5678(目标应该是鳄梨/香瓜/西瓜)。
如何用单一正则表达式来解决这个问题?
发布于 2021-09-10 22:41:39
使用
[^/:\s]+(?:/[^/:\s]+){2}见正则证明。
解释
--------------------------------------------------------------------------------
[^/:\s]+ any character except: '/', ':', whitespace
(\n, \r, \t, \f, and " ") (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (2 times):
--------------------------------------------------------------------------------
/ '/'
--------------------------------------------------------------------------------
[^/:\s]+ any character except: '/', ':',
whitespace (\n, \r, \t, \f, and " ") (1
or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
){2} end of grouping发布于 2021-09-10 22:45:31
您似乎在寻找不包含斜杠或冒号的部件,所以[^/:]+/[^/:]+/[^/:]+。
https://stackoverflow.com/questions/69138575
复制相似问题