【问题标题】:Python Regex - remove all "." and special characters EXCEPT the decimal pointPython 正则表达式 - 删除所有“。”和特殊字符,小数点除外
【发布时间】:2021-10-11 03:25:08
【问题描述】:

我有一些带有多个“.”的句子。

如何删除所有特殊字符和 '.'数据中除小数点外?

输入示例是

What? The Census Says It’s Counted 99.9 Percent of Households. Don’t Be Fooled.

我想删除所有“。” s 和特殊字符,小数点除外'。'

输出应该是这样的

What The Census Says Its Counted 99.9 Percent of Households Dont Be Fooled

我试过了,

regex = re.compile('[^ (\w+\.\w+)0-9a-zA-Z]+')
regex.sub('', test)

但是输出是

What The Census Says Its Counted 99.9 Percent of Households. Dont Be Fooled.

【问题讨论】:

  • 您不能将组放在括号中。试试 '[^ .0-9a-zA-Z]+'。

标签: python-3.x regex regex-group regexp-replace nsregularexpression


【解决方案1】:

使用捕获组仅捕获十进制数字并同时匹配特殊字符(即不是空格和单词字符)。

替换时,只需参考捕获组,以便仅使用捕获的字符。 IE。如果存在,整个匹配将被删除并替换为十进制数。

s = 'What? The Census Says It’s Counted 99.9 Percent of Households. Don’t Be Fooled.'
import re
rgx = re.compile(r'(\d\.\d)|[^\s\w]')
rgx.sub(lambda x: x.group(1), s)
# 'What The Census Says Its Counted 99.9 Percent of Households Dont Be Fooled'

匹配除数字和除特殊字符外的所有字符之间存在的点之外的所有点,然后最后将这些匹配字符替换为空字符串。

re.sub(r'(?!<\d)\.(?!\d)|[^\s\w.]', '', s)
# 'What The Census Says Its Counted 99.9 Percent of Households Dont Be Fooled'
 

【讨论】:

    【解决方案2】:

    您需要以下正则表达式:

    [^ 0-9a-zA-Z](?!(?<=\d\.)\d)
    

    或者,如果您需要一个完全支持 Unicode 的正则表达式:

    (?:_|[^\s\w])(?!(?<=\d\.)\d)
    

    请参阅regex demo详情

    • [^ 0-9a-zA-Z] - 除空格、ASCII 字母或数字以外的任何一个字符
    • (?:_|[^\s\w]) - _ 字符或除空格和单词字符以外的任何一个字符
    • (?!(?&lt;=\d\.)\d) - 如果当前位置的右侧有一个数字紧接在一个数字和一个点之前,则匹配失败。

    Python demo

    import re
    s = 'What? The Census Says It’s Counted 99.9 Percent of Households. Don’t Be Fooled.'
    print(re.sub(r'[^ 0-9a-zA-Z](?!(?<=\d\.)\d)', '', s))
    # => What The Census Says Its Counted 99.9 Percent of Households Dont Be Fooled
    print(re.sub(r'(?:_|[^\s\w])(?!(?<=\d\.)\d)', '', s))
    # => What The Census Says Its Counted 99.9 Percent of Households Dont Be Fooled
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 2011-03-19
      • 2020-02-16
      • 1970-01-01
      相关资源
      最近更新 更多