【问题标题】:Special characters replace using regex in python在python中使用正则表达式替换特殊字符
【发布时间】:2017-11-14 21:00:51
【问题描述】:

只是为了学习,我正在尝试替换键盘中存在的所有特殊字符以替换为underscore'_'

List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./

string I created:

table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""

import re

table1= re.sub(r'!~@#$%^&*()-+={}[]:;<.>?/\'"', '_', table)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib64/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression

无法这样做,我收到了上述错误。

如何使用正则表达式替换字符串中的特殊字符

【问题讨论】:

  • 那是您的确切字符串吗?它没有任何引号。试试table = """...""" 还有,开头的123 是怎么回事?
  • 请注意,)-+ 创建了一个 invalid 范围。始终将- 放在字符类的末尾/开头。是的,并使用一个字符类:)
  • @tobias_k 是的,它是确切的字符串,123 前面没有任何内容
  • 还有\W,它匹配所有非单词字符:re.sub(r'\W', '_', some_string)docs.python.org/3/library/re.html#regular-expression-syntax
  • @Blurp 好点,但这也将取代例如空白。不过可能会使用[^\w\s] 之类的东西,具体取决于OP 想要替换的内容。此外,似乎有像 | 这样的字符不能被替换(不过可能是问题中的错误)。

标签: python regex


【解决方案1】:

您可以使用re.escape 转义字符串中的所有特殊正则表达式字符,然后将转义的字符串包含在[...] 中,以便匹配其中任何一个。

>>> re.sub("[%s]" % re.escape('!~@#$%^&*()-+={}[]:;<.>?/\''), '_', table)
'123____________|___"_______\\__,__'

但是,由于您并没有真正将该正则表达式用作正则表达式,因此您可能只是检查每个字符是否在该字符串中:

>>>''.join("_" if c in '!~@#$%^&*()-+={}[]:;<.>?/\'' else c for c in table)
'123____________|___"_______\\__,__'

或者为了加快查找速度,首先从该字符串中的字符创建一个set

>>> bad_chars = set('!~@#$%^&*()-+={}[]:;<.>?/\'')
>>> ''.join("_" if c in bad_chars else c for c in table)

【讨论】:

    【解决方案2】:

    只要放到一个字符类中,重新排列一些字符的位置(即-,转义+):

    import re
    table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""
    
    table1 = re.sub(r'[-\+!~@#$%^&*()={}\[\]:;<.>?/\'"]', '_', table)
    print(table1)
    # 123____________|___________\__,__
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 2018-01-14
      相关资源
      最近更新 更多