如何排除小括号(少于20个字符)中的逗号
Get index of this comma, but (not this , comma). Get other commas like, or ,or, 1,1 2 ,2. (not this ,) BUT (get index of this comma, if more than 20 characters are inside the parentheses)
this example所有逗号索引的预期输出:
[23, 71, 76, 79, 82, 87, 132]
Tags:
使用PyPi正则表达式:
见proof
Python code:
表达解释
您还可以使用PyPi regex module和SKIP FAIL来匹配和排除匹配结果中不需要的字符
在这种情况下,可以在不应匹配逗号的括号之间匹配1-20
解释
\(
匹配(
[^()]{1,20}
匹配除(
或)
之外的任何字符的1-20倍\)
匹配)
(*SKIP)(*FAIL)
从匹配结果中排除字符|
或,
匹配一个逗号Regex demoPython demo
示例代码
输出
正则表达式模式:
(,)|(\([^()]{0,20}\))
这种模式背后的直觉:
(,)
查找所有逗号。这些存储在捕获组1中(\([^()]{0,20}\))
查找中间最多20个字符的所有括号。这些存储在捕获组2中然后,我们可以找到组1中的所有匹配项,只排除长度为20的括号内的逗号
现在要查找这些匹配项的索引,请使用re.finditer()与Match.start()和Match.group()组合使用,以查找组1中每个匹配项的起始索引:
m.start(1)
返回组1匹配的起始索引。由于re.finditer()
返回来自所有捕获组的匹配项,因此添加if m.group(1)
需要为组1找到匹配项(来自其他组的匹配项为None
)编辑:这将忽略内部包含20个或更少字符的括号,这与第一条语句不一致,但与示例中解释的内容一致。如果希望小于20,只需使用
{0,19}
相关问题 更多 >
编程相关推荐