vijay kapoor
vijay kapoor

Reputation: 43

Replacing characters inside a bracket using regex

I have a string which goes like:

str = "hello <abc123> python <is456> awesome"

and I want to replace the characters within brackets with some other characters. Like the above string should give:

"hello lock python lock awesome "

I tried something like:

ss = str.replace("\\<(.*?)\\>", 'lock') 

but this didn't work. So, how can I do this using regex?

Upvotes: 1

Views: 323

Answers (6)

Kartikeya Sharma
Kartikeya Sharma

Reputation: 1383

import re
str="hello <abc123> python <is456> awesome"
re.sub('\<(.*?)\>','lock',str)

Result:

'hello lock python lock awesome'

Explanation

1.\< : < is a meta char and needs to be escaped if you want to match it literally.
2. (.*?) : match everything in a non-greedy way and capture it.
3. > : > is a meta char and needs to be escaped if you want to match it literally.

Upvotes: 1

Anonymous
Anonymous

Reputation: 699

Use below regx:

import re
s = "hello <abc123> python <is456> awesome"
result = re.sub(r'\<[^<>]+\>', "lock", s)

print(result)

Output:

hello lock python lock awesome

Upvotes: 0

Tomas
Tomas

Reputation: 3436

I tried here Following regex, and got 2 match groups, one per each <something> set:

regex = r"^.*(<\S+>).*(<\S+>).*$"

Upvotes: 0

dodopy
dodopy

Reputation: 169

>>> import re
>>> s ="hello <abc123> python <is456> awesome"
>>> re.sub('<.*?>', 'lock', s)
'hello lock python lock awesome'

Upvotes: 1

gmds
gmds

Reputation: 19885

This will do (combining lookbehind/lookahead assertions with non-greedy matching of .):

before = "hello <abc123> python <is456> awesome"
after = re.sub(r'(?<=<).+?(?=>)', 'lock', before)
print(after)

Output:

hello <lock> python <lock> awesome

If you don't want the brackets, then re.sub(r'<.+?>', 'lock', before) should be fine.

Upvotes: 1

han solo
han solo

Reputation: 6590

You could do a simple regex replace like,

>>> import re
>>> str = "hello <abc123> python <is456> awesome"
>>> re.sub(r'<.*?>', 'lock', str)
'hello lock python lock awesome'

Upvotes: 3

Related Questions