我有一个看起来像这样的字符串:
(((ENGL 210) or (COMM 243) or (COMM 205)) and (ECEN 314) and (ECEN 325))
我想把它改造成:
((ENGL 210 or COMM 243 or COMM 205) and ECEN 314 and ECEN 325)
基本上将 (cccc ddd)
形式的字符串中的所有内容映射到 cccc ddd
,其中 c
是一个字符,d
是一个数字。
我知道我可以使用 re
提取所有此类字符串,但我想将它们映射回新格式。最干净的方法是什么?
谢谢。
最佳答案
import re
t = '(((ENGL 210) or (COMM 243) or (COMM 205)) and (ECEN 314) and (ECEN 325))'
re.sub(r'\(([A-Z]{4} [\d]{3})\)', r'\1', t)
结果
'((ENGL 210 or COMM 243 or COMM 205) and ECEN 314 and ECEN 325)'
解释,re.sub 第一个参数
r'
is going to define a regular expresion inside single quotes
\(
is to match the opening parenthesis, this is the one that you want to remove
(
opening prenthesis to define a new "group". The things inside this will be stored as a matching "group" as regex group number 1matching group #1
[A-Z]{4}
match four characters uppercase letter
match also a space
[\d]{4}
match also four digits
)
关闭组号1
\)
关闭匹配括号(您要删除的另一个)
'
关闭正则表达式
解释,re.sub 第二个参数
r'
is going to define a regular expresion inside single quotes
\1
restore the group number one matched in previous argument
'
关闭正则表达式
关于python - 带有正则表达式的映射列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31632060/