仅在文本的选定部分使用正则表达式修改

2024-07-05 11:49:16 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下字符串:

s = "In $ \mathcal{N}=4$ we fix them completely through the duality to null"

假设我正在使用以下命令进行文本清理:

new_s = s.replace('(', ' ')
new_s = re.sub(r'[^\x00-\x7F]+',' ', new_s)

有没有办法修改除$$中的字符串以外的所有字符串

谢谢


Tags: theto字符串in文本命令newfix
2条回答

re.sub直接与方法一起使用作为替换:

regex = re.compile(r'(\$[^$]*\$)|[^\x00-\x7F]+|\(')
print(regex.sub(lambda m: m.group(1) or " ", s))

proof online

它有什么作用

  1. (\$[^$]*\$)|[^\x00-\x7F]+|\(使用(\$[^$]*\$)将两个美元符号之间的所有字符捕获到ID为1的捕获组中,并在不捕获的情况下将所有非ASCII或(字符与[^\x00-\x7F]+|\(匹配
  2. 如果第一个替代项匹配,则字符串中不会替换任何内容(因为m.group(1)会将匹配的内容放回原处),否则,替换项是一个空格
(?<=\$).+(?=\$)

通过使用lookaround regex,我们可以匹配$ ... $中的所有内容

import re

s = "In $ \mathcal{N}=4$ we fix them completely through the duality to null"
regex = re.compile(r'(?<=\$).+(?=\$)', re.M)

# returns you the string containing 
# only the contents inside $ ... $
s = ' '.join(map(str.strip, regex.findall(s)))
print(s)

了解有关lookaround运算符here的详细信息

相关问题 更多 >