【问题标题】:ReGex Parsing Underscore Character [duplicate]正则表达式解析下划线字符[重复]
【发布时间】:2019-02-08 20:05:24
【问题描述】:

我有这句话需要解析。句子如下:

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

任何建议都将不胜感激!

【问题讨论】:

  • 你想删除_吗?使用s = s.replace('_', '')
  • 效果很好,哈哈,谢谢

标签: python regex python-3.x


【解决方案1】:

我猜你想要这样的东西。

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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 2011-07-26
      • 1970-01-01
      相关资源
      最近更新 更多