I have the following code to match an escaped string:
我有以下代码来匹配转义字符串:
match_str = r'''(["/']).*?(?<!\\)(\\\\)*\1'''
test_str = r'''"This is an \"escaped\" string" and this isn't.'''
mo = re.match(match_str, test_str)
if mo:
print mo.group()
which works fine.
哪个工作正常。
However, while I understand I need the groups in there to handle the repetition, etc., I'm not interested in using the groups after the match. I know I can just call mo.group(0)
and get the whole thing, but for what I am doing it would be helpful if it could behave as if no groups were found in this type of case, i.e. that mo.groups()
would return (None)
.
然而,虽然我知道我需要那里的小组来处理重复等,但我对比赛后使用小组不感兴趣。我知道我可以调用mo.group(0)来获取整个事情,但是对于我正在做的事情,如果它可以表现得好像在这种情况下没有找到任何组,即mo.groups( )将返回(无)。
Is there any way to do this?
有没有办法做到这一点?
EDIT: If it helps, I'm trying to do something like this:
编辑:如果它有帮助,我正在尝试做这样的事情:
ma = [myclass("regex1nogroups", [func1]),
myclass("regex2twogroups", [func2, func3]),
myclass("regex3fourgroups", [func4, func5, func6, func7]),
myclass("regex4nogroups", [func8])]
for mc in ma:
mo = re.match(mc.pattern, str_to_match)
if mo:
for n in range(len(mc.funclist)):
result = mo.group(n+1 if mo.groups() else 0)
mc.funclist[n](result)
using the length of the list of functions to determine how many groups the regex should produce. I could add an extra flag member to myclass
to be true if I want to just assume there are no groups, but it would be nice to avoid this.
使用函数列表的长度来确定正则表达式应该生成多少组。如果我想假设没有组,我可以向myclass添加一个额外的标志成员,但是避免这种情况会很好。
2 个解决方案
#1
3
Just add in ?:
and you get a non-capturing group:
只需添加?:并获得一个非捕获组:
(?:\\\\)
#2
0
I ended up just approaching the problem in a different way, and taking the obvious step of looking at the length of the function list, rather than looking at re.groups()
:
我最后只是以不同的方式处理问题,并采取明显的步骤来查看函数列表的长度,而不是查看re.groups():
ma = [myclass("regex1nogroups", [func1]),
myclass("regex2twogroups", [func2, func3]),
myclass("regex3fourgroups", [func4, func5, func6, func7]),
myclass("regex4nogroups", [func8])]
for mc in ma:
mo = re.match(mc.pattern, str_to_match)
if mo:
for n,f in enumerate(mc.funclist):
result = mo.group(n+1 if len(mc.funclist) > 1 else 0)
f(result)
#1
3
Just add in ?:
and you get a non-capturing group:
只需添加?:并获得一个非捕获组:
(?:\\\\)
#2
0
I ended up just approaching the problem in a different way, and taking the obvious step of looking at the length of the function list, rather than looking at re.groups()
:
我最后只是以不同的方式处理问题,并采取明显的步骤来查看函数列表的长度,而不是查看re.groups():
ma = [myclass("regex1nogroups", [func1]),
myclass("regex2twogroups", [func2, func3]),
myclass("regex3fourgroups", [func4, func5, func6, func7]),
myclass("regex4nogroups", [func8])]
for mc in ma:
mo = re.match(mc.pattern, str_to_match)
if mo:
for n,f in enumerate(mc.funclist):
result = mo.group(n+1 if len(mc.funclist) > 1 else 0)
f(result)