替换<中的空格。 ...>子

时间:2018-04-10 05:22:16

标签: python regex string replace substring

提前致谢。 我想用一些其他字符替换特定字符串中的空格,例如&#39; _&#39;或者&#39; ~&#39;或者只是删除空格,但仅限于某些字符之间的子字符串,如&#39; < >&#39;或者&#39; " "&#39;。例如

config snmp trapreceiver create < community name > < trap receiver IP >

应该成为:

config snmp trapreceiver create < community_name > < trap_receiver_IP >

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:0)

使用正则表达式:

import re
s = """config snmp trapreceiver create < community name > < trap receiver IP >"""
print(re.sub('\<.*?\>', lambda x: '_'.join(x.group(0).replace("< ", "<").replace(" >", ">").split()), s))

<强>输出:

config snmp trapreceiver create <community_name> <trap_receiver_IP>

答案 1 :(得分:0)

有一种更简单的方法可以完成这项工作(如果您不熟悉正则表达式以及如何在Python中使用lambda)

Python有一组丰富的内置字符串函数,可以帮助你玩字符串,看看this它将帮助你入门。

回答你的问题:

这是我的代码:

a = 'community name'
b = 'trap_receiver_IP'

c = 'config snmp trapreceiver create < community name > < trap receiver IP >'
s = c.find( "<" )

def replaceSpace( stringToBeReplaced ):
    aa = stringToBeReplaced.replace( " ", "_" )
    print( aa )
    return aa

def replaceDash( stringToBeReplaced ):
    bb = stringToBeReplaced.replace( "_", " " )
    print( bb )
    return bb

def getSubstring( stringToBeProcessed, stringResult = None ):


    string = stringToBeProcessed
    resultlst = []
    for i in range(0, 2):
        start = string.find( "<" )
        end = string.find( ">" )

        result = string[ start+2 :end-1 ]
        resultlst.append( result )
        string = stringToBeProcessed[end+1:]

    return resultlst 

subStringLst = getSubstring('config snmp trapreceiver create < community name > < trap receiver IP >' )

subStringLst[0] = replaceSpace( subStringLst[0] )
subStringLst[1] = replaceDash( subStringLst [1] )

finalStr = c[:s] + "<" + subStringLst[0] + ">" + " <" + subStringLst[1] + ">"
print( finalStr )

答案 2 :(得分:0)

如果你想尝试没有正则表达式,那么这里是纯python方法:

data="""config snmp trapreceiver create < community name > < trap receiver IP > sql things also comes in because < sammm name >"""

splitted_data=data.split()

chunks=[]

def _approach(list_):
    flag=True
    store=[]
    track=[]
    previous=[]
    for i,j in enumerate(list_):
        if j=='<':
            if previous:
                chunks.append(previous)
            previous=[]
            track.append(i)
            flag=False

            store.append(j)
        elif j=='>':
            store.append('>')
            chunks.append(store)
            track=[]
            flag=True
            store=[]
        elif flag==False:
                store.append(j)
        else:
            previous.append(j)





_approach(splitted_data)


new_final=[]

for j,i in enumerate(chunks):
    if i[0]=='<':
        new_final.append(i[0]+"_".join(i[1:-1])+i[-1])
    else:
        for ia in i:
            new_final.append(ia)

print(*new_final)

输出:

config snmp trapreceiver create <community_name> <trap_receiver_IP> sql things also comes in because <sammm_name>

答案 3 :(得分:0)

这似乎可以匹配要替换的空格

(?<!\<)(\s+)(?=(?!\>)[^\<\>\n]*\>)

Demo ,,,其中仅匹配和捕获要替换的空格

在python脚本中,它可能就像这样

ss="""config snmp trapreceiver create < community name > < trap receiver IP >
config snmp trapreceiver create < community name > < trap receiver IP >"""

import re
regx= re.compile(r'(?<!\<)(\s+)(?=(?!\>)[^\<\>\n]*\>)')
print(regx.sub("_",ss))

输出

config snmp trapreceiver create < community_name > < trap_receiver_IP >
config snmp trapreceiver create < community_name > < trap_receiver_IP >