1

below is string Register addr = [0x0128], data = [0x59]

i want to get 0x59 not 0x0128 by using Regex

this is my code

import re
data = "Register addr = [0x0128], data = [0x59]"
pattern = re.compile("d[.]]")
re.findall(pattern, data)

i don't have idea to get exact 0x59 could you help me?

5
  • is 0x59 the only string you wanna extract? or it may change? Commented Feb 21, 2020 at 2:17
  • is 0x59 always followed by word 'data' & '=' and within square brackerts? Commented Feb 21, 2020 at 2:17
  • only extract @Mox Commented Feb 21, 2020 at 2:17
  • @moys yes it is always followed that Commented Feb 21, 2020 at 2:19
  • Reverse the string, reverse the pattern, extract the first match. Or use finditer/findall with a appropriate pattern and keep the last. Maybe r'(0x[^\]]+)' Commented Feb 21, 2020 at 2:26

3 Answers 3

3

You can do

data = "Register addr = [0x0128], data = [0x59]"
print(re.findall(r'(?<=data\s=\s)\[(\w*)\]',data))

Output

['0x59']

you can also do print(re.search(r'(?<=data\s=\s)\[(\w*)\]',data).group(1))

output

Note that re.search returns ONLY the first match (it stops serching after the first match has been found.

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

Comments

1

If you're only seeking to find 0x59 just do a direct search for it.

pattern = re.compile(r"0x59")

If you want to find all hex codes beginning with 0x located within []

pattern = re.compile(r"\[0x.*?\]")
re.findall(pattern, data)
#['[0x0128]', '[0x59]']

Comments

1

The easy way to do it is via:

print(re.sub(']', '', data.partition("data = [")[2]))

.partition splits the string on data = [ giving a tuple & [2] selects the part of the string after data = [.

re.sub removes all of the ] from that string.

Note, both 0x59 and 0x0128 are valid hex numbers.

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.