【问题标题】:regex error : raise error, v # invalid expression正则表达式错误:引发错误,v # 无效表达式
【发布时间】:2017-01-25 18:53:46
【问题描述】:

我有一个变量device='A/B/C/X1' 在另一个文件中被注释掉了。同一设备可以有多个实例,例如'A/B/C/X1@1'..@2 等。所有这些设备都在另一个文件中注释掉,前缀为*

我想删除*,但不影响'A/B/C/X**10**'等类似设备。

我尝试使用正则表达式来简单地使用以下代码行替换模式,但我收到了 InvalidExpression 错误。

line=re.sub('^*'+device+'@',device+'@',line)

请帮忙。

【问题讨论】:

    标签: python regex python-2.7


    【解决方案1】:

    您需要转义星号,因为它在正则表达式语法中具有含义: line=re.sub(r'^\*'+device+'@',device+'@',line).

    转义用于构造正则表达式的变量也是一个好主意: line=re.sub(r'^\*'+re.escape(device)+'@',device+'@',line)

    【讨论】:

    • 或者在你的正则表达式字符串前面放一个 r
    • 为了记录它在markdown OP中也有特殊的含义。这就是为什么你到处都是随机的斜体和粗体文本。
    • @Emaro 这还不够,因为它只会禁用该字符串中反斜杠的转义,仅此而已。
    • 谢谢大家,知道了。
    【解决方案2】:
    def replace_all(text):
        if text in ['*']:
            text = text.replace(text, '')
        return text
    
    my_text = 'adsada*asd*****dsa*****'
    
    result = "".join(map(replace_all, my_text))
    print result
    

    或者

    import re
    my_text = 'adsada*asd*****dsa*****'
    print (re.sub('\*', '', my_text))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2016-11-19
      相关资源
      最近更新 更多