Replace nth occurrence of substring in string

后端 未结 10 2361
面向向阳花
面向向阳花 2020-11-27 06:51

I want to replace the n\'th occurrence of a substring in a string.

There\'s got to be something equivalent to what I WANT to do which is

mystring.repl

10条回答
  •  渐次进展
    2020-11-27 07:43

    I had a similar need, i.e to find the IPs in logs and replace only src IP or dst IP field selectively. This is how i achieved in a pythonic way;

    import re
    
    mystr = '203.23.48.0 DENIED 302 449 800 1.1 302 http d.flashresultats.fr  10.111.103.202 GET GET - 188.92.40.78 '
    src = '1.1.1.1'
    replace_nth = lambda mystr, pattern, sub, n: re.sub(re.findall(pattern, mystr)[n - 1], sub, mystr)
    result = replace_nth(mystr, '\S*\d+\.\d+\.\d+\.\d+\S*', src, 2)
    print(result)
    

提交回复
热议问题