我有一个变量device='A/B/C/X1'
,在另一个文件中注释掉了。同一设备可能有多个实例,例如'A/B/C/X1@1'
,..@2
等。所有这些设备都在另一个带有前缀*
的文件中注释掉。
我想删除*
,但不会影响'A/B/C/X**10**'
等类似设备。
我尝试使用正则表达式简单地使用以下代码行替换模式,但我收到InvalidExpression
错误。
line=re.sub('^*'+device+'@',device+'@',line)
请帮忙。
答案 0 :(得分:3)
你需要转义星号,因为它具有正则表达式语法的含义:
get(url)
ERROR: MbedTLS error code -30592: SSL - A fatal alert message was received from our peer
in macro expansion at /home/david/.julia/v0.5/MbedTLS/src/error.jl:4 [inlined]
in handshake(::MbedTLS.SSLContext) at /home/david/.julia/v0.5/MbedTLS/src/ ssl.jl:145
in open_stream(::HttpCommon.Request, ::MbedTLS.SSLConfig, ::Float64, ::Nullable{URIParser.URI}, ::Nullable{URIParser.URI}) at /home/david/.julia/ v0.5/Requests/src/streaming.jl:209
in #do_stream_request#23(::Dict{AbstractString,AbstractString}, ::Void, ::Void, ::Void, ::Array{Requests.FileParam,1}, ::Void, ::Dict{Any,Any}, ::Bool, ::Int64, ::Array{HttpCommon.Response,1}, ::MbedTLS.SSLConfig, ::Bool, ::Bool, ::Bool, ::Nullable{URIParser.URI}, ::Nullable{URIParser.URI}, ::Requests.#do_stream_request, ::URIParser.URI, ::String) at /home/david/.julia /v0.5/Requests/src/Requests.jl:361
in do_stream_request(::URIParser.URI, ::String) at /home/david/.julia/v0.5/ Requests/src/Requests.jl:324
in #do_request#22(::Array{Any,1}, ::Function, ::URIParser.URI, ::String) at / home/david/.julia/v0.5/Requests/src/Requests.jl:291
in #get#29(::Array{Any,1}, ::Function, ::URIParser.URI) at /home/david/.julia/ v0.5/Requests/src/Requests.jl:424
in #get#28(::Array{Any,1}, ::Function, ::String) at /home/david/.julia/v0.5/ Requests/src/Requests.jl:423
in get(::String) at /home/david/.julia/v0.5/Requests/src/Requests.jl:423
。
转义用于构造正则表达式的变量也总是一个好主意:
line=re.sub(r'^\*'+device+'@',device+'@',line)
答案 1 :(得分:0)
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))