我正在使用regexps在python中开发一种“自定义脚本解析器”。 请不要回答关于regexp是不是这种操作的好解决方案...解释为什么我选择使用regexp很长(并且是偏离主题的),即使我知道使用的问题用于解析的正则表达式。
现在我继续提问。我们从这个场景开始:
这是我将从文件中读取的行,我需要使用正则表达式进行解析:
something = { call _ "string to ""capture"" " } #non consumed
现在我可以这样做:
import re
regex1 = re.compile(r'^([^"]*?)(_?)\s*"((?:""|[^"])*)"')
mystr = r'something = { call _ "string to ""capture"" " } #non consumed'
mymatch = re.search(regex1, mystr)
所以我可以获得这些捕获组:
我需要知道这些群组,因此使用re.search
很好(因为我可以使用mymatch.group(n)
来检查单个捕获群组的值。)
但是...在我使用从1
到3
的所有组之后,我将需要减少mystr,因此它将仅包含“'successl'regexp”中的“非消耗字符串”
我可以这样做:
mystr = mystr[ len(mymatch.group(0)): ]
所以一个工作代码就是这个:
import re
regex1 = re.compile(r'^([^"]*?)(_?)\s*"((?:""|[^"])*)"')
mystr = r'something = { call _ "string to ""capture"" " } #non consumed'
mymatch = re.search(regex1, mystr)
# code here that uses mymatch.group(n)
mystr = mystr[ len(mymatch.group(0)): ] # clear from mystr what was parsed by the regexp
但我想知道是否有其他方法可以做到这一点。 您能否建议我提供的其他代码方法不同?“
搜索:
Not useful:它只询问有关替换的问题,而不是关于单个匹配组的问题。在这里,我想问如何以一种好的方式一起做两个动作
Not useful:对于(几乎)与第一个链接相同的原因