【发布时间】:2011-07-20 20:17:08
【问题描述】:
当我使用以下 python 正则表达式执行下述功能时,我收到错误 Unexpected end of Pattern。
正则表达式:
modified=re.sub(r'^(?i)((?:(?!http://)(?!testing[0-9])(?!example[0-9]).)*?)(?-i)
(CODE[0-9]{3})(?!</a>)',r'<a href="http://productcode/\g<1>">\g<1></a>',input)
此正则表达式的目的:
输入:
CODE876
CODE223
matchjustCODE657
CODE69743
code876
testing1CODE888
example2CODE098
http://replaced/CODE665
应该匹配:
CODE876
CODE223
CODE657
CODE697
并将出现的地方替换为
http://productcode/CODE876
http://productcode/CODE223
matchjusthttp://productcode/CODE657
http://productcode/CODE69743
不应匹配:
code876
testing1CODE888
testing2CODE776
example3CODE654
example2CODE098
http://replaced/CODE665
最终输出
http://productcode/CODE876
http://productcode/CODE223
matchjusthttp://productcode/CODE657
http://productcode/CODE69743
code876
testing1CODE888
example2CODE098
http://replaced/CODE665
编辑和更新 1
modified=re.sub(r'^(?i)((?:(?!http://)(?!testing[0-9])(?!example[0-9]).)*?)(CODE[0-9]{3})(?!</a>)',r'<a href="http://productcode/\g<1>">\g<1></a>',input)
错误不再发生。但这与需要的任何模式都不匹配。匹配组或匹配本身是否存在问题。因为当我这样编译这个正则表达式时,我的输入不匹配。
编辑和更新 2
f=open("/Users/mymac/Desktop/regex.txt")
s=f.read()
s1 = re.sub(r'((?!http://|testing[0-9]|example[0-9]).*?)(CODE[0-9]{3})(?!</a>)',
r'\g<1><a href="http://productcode/\g<2>">\g<2></a>', s)
print s1
输入
CODE123 CODE765 testing1CODE123 example1CODE345 http://www.coding.com/CODE333 CODE345
CODE234
CODE333
输出
<a href="http://productcode/CODE123">CODE123</a> <a href="http://productcode/CODE765">CODE765</a> testing1<a href="http://productcode/CODE123">CODE123</a> example1<a href="http://productcode/CODE345">CODE345</a> http://www.coding.com/<a href="http://productcode/CODE333">CODE333</a> <a href="http://productcode/CODE345">CODE345</a>
<a href="http://productcode/CODE234">CODE234</a>
<a href="http://productcode/CODE333">CODE333</a>
正则表达式适用于原始输入,但不适用于来自文本文件的字符串输入。
更多结果请参见输入 4 和 5 http://ideone.com/3w1E3
【问题讨论】:
-
code876应该怎么做?CODE8765? -
@thinkcool:编辑您的问题以包含 code876 和 CODE8765 示例。注意:您的模式不会尝试限制 CODE 之后的位数。同样按照建议,使用 re.VERBOSE 以便您自己更好地了解它在做什么。
-
@thinkcool: CODE69743 在所需的输出中但不在输入中
-
@thinkcool: CODE123XYZ 的输入怎么办?
标签: python regex pattern-matching