0

I want to substitute the following:

 default by <http://www.mycompany.com/>
 db: by <http://www.mydbcompany.com/>

I have data of the following format:

   <a> <b> <c>.
   <d> db:connect <e>.
   db:start <f> <g>.
   <h> <i> "hello".

Now I want to transform this data into the following form:

   <http://www.mycompany.com/a> <http://www.mycompany.com/b> <http://www.mycompany.com/c>.
   <http://www.mycompany.com/d> <http://www.mydbcompany.com/connect> <http://www.mycompany.com/e>.
   <http://www.mydbcompany.com/start> <http://www.mycompany.com/f> <http://www.mycompany.com/g>.
   <http://www.mycompany.com/h> <http://www.mycompany.com/i> "hello".

Now the way I am trying to achieve the desired format is to separate to break each line by using:

line1=re.split('(?<=)\s+(?=<)',line)

and then for line1[0], line1[1], line1[2] I try to

substitute < by <http://www.mycompany.com/

However, my problem is that this approach does not work for db: and quotes. Is there some way by which I may achieve the desired output in python

1 Answer 1

1

Why not re.sub?

S = """\
<a> <b> <c>.
<d> db:connect <e>.
db:start <f> <g>.
<h> <i> "hello".
"""

import re

expand_tags = re.sub(r"<(.*?)>", r"<http://www.mycompany.com/\1>", S)
expand_db = re.sub(r"db:(.*?)\s", r"<http://www.mydbcompany.com/\1>", expand_tags)

print(expand_db)
#>>> <http://www.mycompany.com/a> <http://www.mycompany.com/b> <http://www.mycompany.com/c>.
#>>> <http://www.mycompany.com/d> <http://www.mydbcompany.com/connect><http://www.mycompany.com/e>.
#>>> <http://www.mydbcompany.com/start><http://www.mycompany.com/f> <http://www.mycompany.com/g>.
#>>> <http://www.mycompany.com/h> <http://www.mycompany.com/i> "hello".

The \1 in the second part means whatever was inside the brackets in the first part, so you can match the pattern and put it in the replacement. It seems like an odd thing to do, though, so you might want to reconsider the whole design.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.