【问题标题】:How to replace all \W (none letters) with exception of '-' (dash) with regular expression?如何用正则表达式替换除'-'(破折号)之外的所有\W(无字母)?
【发布时间】:2014-12-21 10:27:51
【问题描述】:

我想替换所有 \W 而不是字母,除了 - 破折号到空格,即:

  1. black-white 会给black-white
  2. black#white 会给black white

我非常了解正则表达式,但我不知道如何处理它。

考虑到我想使用 Unicode,所以 [a-zA-Z] 不是 \w 就像只有英文一样。 考虑到我更喜欢 Python re 语法,但可以阅读其他建议。

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    使用否定字符类:(\W 等价于[^\w][^-\w] => \W 除了-

    >>> re.sub(r'[^-\w]', ' ', 'black-white')
    'black-white'
    >>> re.sub(r'[^-\w]', ' ', 'black#white')
    'black white'
    

    如果你使用regex包,你可以使用nested sets, set operations

    >>> import regex
    >>> print regex.sub(r'(?V1)[\W--[-]]', ' ', 'black-white')
    black-white
    >>> print regex.sub(r'(?V1)[\W--[-]]', ' ', 'black#white')
    black white
    

    【讨论】:

      【解决方案2】:

      我会使用negative lookahead,如下所示,

      >>> re.sub(r'(?!-)\W', r' ', 'black-white')
      'black-white'
      >>> re.sub(r'(?!-)\W', r' ', 'black#white')
      'black white'
      

      (?!-)\W 开头的否定前瞻断言我们要匹配的字符将是 \W(非单词字符列表)中的任何字符,但不是连字符 - 中的任何字符。这就像一种减法,即\W - character present inside the negative lookahead(即连字符)。

      DEMO

      【讨论】:

      • 你也可以使用这个-(*SKIP)(*F)|\W regex101.com/r/sS1qO8/3 但是正则表达式模块不支持这个。
      • 做更好的分词的好主意。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 2022-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多