我有一个正则表达式,用于在Python代码中获取字符串:
x1 = re.compile('''((?P<unicode>u?)(?P<c1>'|")(?P<data>.+?)(?P<c2>'|"))''')我想提取这个正则表达式的data和c1,c2部分,以生成一个替换字符串(如果是c1 == c2)
类似于:
repl = "u<c1><data><c2>"我该怎么做??
这在一行中是可行的还是通过使用re.sub
更新
我的新代码:
x1 = re.compile('''(?P<unicode>u?)(?P<c>'|")(?P<data>.*?)(?P=c)''')
def repl(match):
if '#' in match.string:
### Confused
return "u%(c)s%(data)s%(c)s" % m.groupdict()
fcode = '\n'.join([re.sub(x1,repl,i) for i in scode.splitlines()])在这里,我有问题来确定如何不改变评论中的字符串,我要做什么来忽略这些评论??
发布于 2013-03-17 04:17:57
假设你有一个模式:
pattern = r'''(?P<unicode>u?)(?P<c>'|")(?P<data>.*?)(?P=c)''' # did a little tweak匹配字符串:
m = re.search(pattern, "print('hello')")你得到了什么:
>>> m.groups()
('', '"', 'hello')
>>> m.groupdict()
{'c': '"', 'unicode': '', 'data': 'hello'}现在你可以用这些做你想做的任何事情:
>>> 'u{c}{data}{c}'.format_map(m.groupdict())
'u"hello"'也许您正在使用Python2.x:
>>> 'u{c}{data}{c}'.format(**m.groupdict())
'u"hello"'甚至连你都喜欢老%
>>> "u%(c)s%(data)s%(c)s" % m.groupdict()
'u"hello"'编辑的
regex解决方案不能正确处理某些情况。
因此,我使用了一个2to3黑客(实际上是3到2,仍然不能解决所有问题):
cd /usr/lib/python3.3/lib2to3/fixes/
cp fix_unicode.py fix_unicode33.py编辑fix_unicode33.py
-_literal_re = re.compile(r"[uU][rR]?[\'\"]")
+_literal_re = re.compile(r"[rR]?[\'\"]")
-class FixUnicode(fixer_base.BaseFix):
+class FixUnicode33(fixer_base.BaseFix):
- new.value = new.value[1:]
+ new.value = 'u' + new.value现在2to3 --list | grep unicode33应该输出unicode33
然后可以运行2to3 -f unicode33 py3files.py。
记得在之后删除fix_unicode33.py
注意到:在Python3 ur"string"中抛出SyntaxError。这里的逻辑很简单,修改它以达到您的目标。
发布于 2013-03-18 04:46:49
我最后得到的长代码。
x1 = re.compile('''(?P<unicode>u?)(?P<c>'|")(?P<data>.*?)(?P=c)''')
def in_string(text,index):
curr,in_l,in_str,level = '',0,False,[]
for c in text[:index+1]:
if c == '"' or c == "'":
if in_str and curr == c:
instr = False
curr = ''
in_l -= 1
else:
instr = True
curr = c
in_l += 1
level.append(in_l)
return bool(level[index])
def repl(m):
return "u%(c)s%(data)s%(c)s" % m.groupdict()
def handle_hashes(i):
if i.count('#') == 1:
n = i.find('#')
else:
n = get_hash_out_of_string(i)
return re.sub(x1,repl,i[:n]) + i[n:]
def get_hash_out_of_string(i):
n = i.find('#')
curr = i[:]
last = (len(i)-1)-''.join(list(reversed(i))).find('#')
while in_string(curr,n) and n < last:
curr = curr[:n]+' '+curr[n+1:]
n = curr.find('#')
return nhttps://stackoverflow.com/questions/15457310
复制相似问题