【问题标题】:Remove period[.] and comma[,] from string if these does not occur between numbers如果数字之间没有出现句点 [.] 和逗号 [,] 从字符串中删除
【发布时间】:2017-03-19 14:56:27
【问题描述】:

只有在数字之间没有出现逗号和句点时,我才想从文本中删除它们。

所以,下面的文字应该返回

"This shirt, is very nice. It costs DKK ,.1.500,00,."

"This shirt is very nice It costs DKK 1.500,00"

我试过了

text = re.sub("(?<=[a-z])([[$],.]+)", " ", text) 

但它不会替代文本中的任何内容。

【问题讨论】:

    标签: python regex python-2.7


    【解决方案1】:

    你可以试试这个:

    >>> s = "This shirt, is very nice. It costs DKK ,.1.500,00,."
    >>> re.sub('(?<=\D)[.,]|[.,](?=\D)', '', s)
    'This shirt is very nice It costs DKK 1.500,00'
    

    使用肯定的lookbehind断言来检查符号前面是否有一个非数字字符,以及使用肯定的lookahead断言在同一字符集上的alternation 检查它后面是一个非数字字符。

    https://regex101.com/r/54STMM/4

    【讨论】:

    • 谢谢。我发现为什么上面的表达式不能转换 u.s. 有点棘手。给我们?
    • 请注意,最后一个字符(末尾的逗号)仍有问题。
    • 而且它也不能使用点/逗号作为字符串的第一个字符。
    • @dekel 放弃了该组,没有注意到它对另一个断言的绑定效果。
    猜你喜欢
    • 2011-06-24
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多