[英]Python match and replace, what I do wrong?
I have reg exp for match some data (is it here ) and now I try to replace all matched data with single :
characetr 我有用于匹配某些数据的reg exp( 在这里 ),现在我尝试将所有匹配的数据替换为single :
characetr
test_str = u"THERE IS MY DATA"
p = re.compile(ur'[a-z]+([\n].*?<\/div>[\n ]+<div class="large-3 small-3 columns">[\n ]+)[a-z]+', re.M|re.I|re.SE)
print re.sub(p, r':/1',test_str)
I try it on few other way but it's not replace any or replace not only matched but whole pattern 我以其他几种方式尝试它,但它不能替换任何东西,或者不仅替换匹配的而且替换整个模式
1)It's backslash issue. 1)这是反斜杠问题。
Use : print re.sub(p, r':\\1',test_str)
not print re.sub(p, r':/1',test_str)
. 使用: print re.sub(p, r':\\1',test_str)
不print re.sub(p, r':/1',test_str)
。
2)You are replacing all the pattern with :\\1
, that means replace all the text with :
followed by the first group in the regex. 2)您要用:\\1
替换所有模式,这意味着要用:
替换所有文本,然后是正则表达式中的第一组。
To replace just the first group inside the text you should add two groups , before the first and after. 要仅替换文本中的第一个组,应在第一个和之后添加两个组。 I hope this will fix the issue: 我希望这可以解决问题:
test_str = u"THERE IS MY DATA"
p = re.compile(ur'([a-z]+)([\n].*?<\/div>[\n ]+<div class="large-3 small-3 columns">[\n ]+)([a-z]+)', re.M|re.I|re.SE)
print re.sub(p, r'\1:\2\3',test_str)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.