python - 带有正则表达式的映射列表

标签 python regex

我有一个看起来像这样的字符串:

(((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 1

matching 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/

相关文章:

python - Pandas 子图布局在这种情况下不起作用

python - 我如何使用字典理解来计算文档中每个单词的出现次数

Python正则表达式: making multiple different substitutions in a single pass using Groups

python - 使用 python 如何在文本文件的选择行中插入字符串,其中插入的字符串取决于行的内容和已知的映射?

python - 在 try 中的 Nose 测试中手动添加错误 - except

python - 创建一个在调用时将递增 1 的函数

python - 在黑白图片中的特定颜色周围添加边框

javascript - 如何在 Javascript 中以正斜杠结束正则表达式

regex - 带有 {} grep 和正则表达式的大括号 : Why does it exceed the maximum value?

java - 创建一个在字符串开头没有两个字符匹配的正则表达式。