正则表达式,函数替换字符串
正则表达式,函数替换字符串
模式字符串中,\用来查找\,就是不转义
?表示懒惰模式
def replace_cite(src):
src = src.group()
print('src=',src)
replaced_str = '<cite_start>{}<site_end>'.format(src[7:-1])
return replaced_str
test_text = r'start ~\cite{cong2011sparse},recommendation~\cite{wang2012event,bbb} (see Fig.~\ref{fig:intro}), '
a = re.sub(r'~\\cite\{.*?\}', replace_cite, test_text)
print(a)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# vscode正则替换:
参考: https://www.jianshu.com/p/492811ba1052 (opens new window)
将
<img src="../assets/img/chairman_indecate1.jpg" alt style="height:300px; padding-top:30px; "/>
替换为
<img v-lazy="require('../assets/img/chairman_indecate1.jpg')" alt style="height:300px; padding-top:30px; "/>
1
2
3
4
5
2
3
4
5
正则表达式替换:
将:
mg(.*)src="(.*)"(.*)/>
替换为:
<img$1v-lazy="require('$2')"$3/>
1
2
3
4
5
2
3
4
5
说明:
- .*:匹配任意次数的除了回车符和换行符以外的所有字符
- ():分组,后面可以用$1、$2...进行捕获
# 提取数据
https://blog.csdn.net/weixin_42550871/article/details/108943529 (opens new window)
import re
line = "Cats are smarter than dogs";
searchObj = re.search(r'(.*) are (.*?) ', line, re.M | re.I)
if searchObj:
print("searchObj.group() : ", searchObj.group())
print("searchObj.group(1) : ", searchObj.group(1))
print("searchObj.group(2) : ", searchObj.group(2))
# 执行结果
# searchObj.group() : Cats are smarter
# searchObj.group(1) : Cats
# searchObj.group(2) : smarter
# re.sub()用于替换字符串中的匹配项
import re
phone = "2004-959-559 # 这是一个国外电话号码"
# 删除字符串中的 Python注释,$匹配字符串的末尾。
# 把匹配到的字符串替换为空字符串
num = re.sub(r'#.*$', "", phone)
print("电话号码是: ", num)
# 电话号码是: 2004-959-559
# 删除非数字(-)的字符串,\D 匹配任意非数字
num = re.sub(r'\D', "", phone)
print("电话号码是 : ", num)
# 电话号码是 : 2004959559
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
编辑 (opens new window)
上次更新: 2022/09/20, 17:39:06