|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import re
string = "in row 100 next to the rowdy guy"
rowWordRegex = re.compile(r"\brow\b")
print(rowWordRegex.sub(r"<span class = \"hi\">\g<0></span>",string))
\g<0>肯定不会是没意义的,反而在你代码中意义非常大!!!
re.sub(pattern, repl, string, count=0, flags=0)
参数:
pattern : 正则中的模式字符串。
repl : 替换的字符串,也可为一个函数。
string : 要被查找替换的原始字符串。
count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
flags : 编译时用的匹配模式,数字形式。
前三个为必选参数,后两个为可选参数。
那这里的pattern就是rowWordRegex = re.compile(r"\brow\b"),
repl就是r"<span class = \"hi\">\g<0></span>"
string就是string也就是"in row 100 next to the rowdy guy"
ok,先把上面这层关系缕清,诶...正则好头大~~~
接下来,我们看这句【r"\brow\b"】的含义,\b:表示字母数字与非字母数字的边界,非字母数字与字母数字的边界,如果这是你用search来看下的话,
re.search(rowWordRegex,string)返回的就是:<re.Match object; span=(3, 6), match='row'>,rowWordRegex 其实也就是将string分为
然后,我们看最后的sub,意思就是以string 的row之前为开头,in和row之间替换为\g<0>之前的,\g<0>就是row,\g<0>之后的就是string row之后的,相当于用row作分割然后替换;
举个例子:
print(rowWordRegex.sub(r'我会在in和row之间 \g<0> 我会在row和100之间',string))
返回的结果:
in 我会在in和row之间 row 我会在row和100之间 100 next to the rowdy guy
好了,不知道你明白没,我头大了,正则...好恶心...
|
|