ReGex解析下划线字符

时间:2019-02-08 20:05:25

标签: python regex python-3.x

我有这句话需要解析。机敏性如下所示:

I'm sure _I_ shan't be able!  I shall be a great deal too far off to trouble myself

我下面需要的结果是:

I'm sure I shan't be able!  I shall be a great deal too far off to trouble myself

表达会是什么样子?

我正在使用的当前表达式是

r'(?!_)\w+' 

但是我得到的结果是:

I'm sure I_ shan't be able!  I shall be a great deal too far off to trouble myself

任何建议,谢谢您!

2 个答案:

答案 0 :(得分:0)

我想你想要这样的东西。

text = "I'm sure _I_ shan't be able!  I shall be a great deal too far off to trouble myself"

print(text.replace('_',''))
#expected output:
#I'm sure I shan't be able!  I shall be a great deal too far off to trouble myself

答案 1 :(得分:0)

您可以使用以下方法删除单词周围的所有下划线:

import re

text = "I'm sure _I_ shan't be able! I shall be a great _deal_ too far off to _trouble_ myself"

result = re.sub(r'(_)(\w+)(_)', r'\2', text)

print(result)  # I'm sure I shan't be able! I shall be a great deal too far off to trouble myself