简体   繁体   中英

Python replace a string with wild characters

I have a string like this:

 jmeter -t xyz.jmx -Jhost=192.111.11.11 -JCEnext=192.111.11.11 ....

xyz.jmx is variable string and can be any name ie abc123.jmx or xyz1.jmx ..

I need to replace

jmeter -t xyz.jmx 

with

jmeter -n -t C:\Automation\Jmeter\xyz.jmx

how can I do this?

You can use Regex : using re.sub

Ex:

import re
s = "jmeter -t xyz.jmx -Jhost=192.111.11.11 -JCEnext=192.111.11.11"
toReplace = r"jmeter -n -t C:\Automation\Jmeter\\"

print(re.sub("jmeter(.*?)\-t\s+", toReplace, s))

Output:

jmeter -n -t C:\Automation\Jmeter\xyz.jmx -Jhost=192.111.11.11 -JCEnext=192.111.11.11

You can try Positive Lookbehind (?<=-t)

import re

pattern =r'(?<=-t)\s(\w.+?\s)'

text='jmeter -t xyz.jmx -Jhost=192.111.11.11 -JCEnext=192.111.11.11 ....'

replaced=re.sub(pattern,r' C:\Automation\Jmeter\xyz.jmx ',text)
print(replaced)

output:

jmeter -t C:\Automation\Jmeter\xyz.jmx -Jhost=192.111.11.11 -JCEnext=192.111.11.11 ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM