Kamal Kant
Kamal Kant

Reputation: 3

python find a pattern in string and enclose it in braces

I am not an expert in regex and trying to do the below.

string 's' can contain pattern 16'h2020:16'h2F20 i.e hexadecimal numbers range. I need to enclose this match in square bracket and return to same string, i.e [16'h2020:16'h2F20].

i did it as:

s = re.sub("\d+'h\d+:\d+'h\d+","[\d+'h\d+:\d+'h\d+]",s)

But its not working as required. Please help.

Upvotes: 0

Views: 62

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174756

Here you need to use capturing group.

s = re.sub(r"(\d+'h\d+:\d+'h\d+F\d+)",r'[\1]',s)

Example:

>>> import re
>>> s = "16'h2020:16'h2F20"
>>> re.sub(r"(\d+'h\d+:\d+'h\d+F\d+)",r'[\1]',s)
"[16'h2020:16'h2F20]"

Upvotes: 2

Related Questions