1

I have a string:

st="[~620cc13778d079432b9bc7b1:Hello WorldGuest]"

I just want the part after ":" and before "]". The part in between can have a maximum length of 64 characters.

The part after "[~" is 24 character UUID.

So the resulting string would be "Hello WorldGuest".

I'm using the following regex:

r"(\[\~[a-z0-9]{24}:)(?=.{0,64})"

But that is only matching the string till ":", I also want to match the ending "]".

1 Answer 1

1

Given:

>>> import re
>>> st = "[~620cc13778d079432b9bc7b1:Hello WorldGuest]"

Two simple ways:

>>> re.sub(r'[^:]*:([^\]]*)\]',r'\1',st)
'Hello WorldGuest'
>>> st.partition(':')[-1].rstrip(']')
'Hello WorldGuest'

If you want to be super specific:

>>> re.sub(r'^\[~[a-z0-9]{24}:([^\]]{0,64})\]$',r'\1',st)
'Hello WorldGuest'

If you want to correct your pattern, you can do:

>>> m=re.search(r'(?:\[~[a-z0-9]{24}:)(?=([^\]]{0,64})\])', st)
>>> m.group(1)
'Hello WorldGuest'

Or with anchors:

>>> m=re.search(r'(?:^\[~[a-z0-9]{24}:)(?=([^\]]{0,64})\]$)', st)
>>> m.group(1)
'Hello WorldGuest'

Note:

I just used your regex for a UUID even though it is not correct. The correct regex for a UUID is:

[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}

But that would not match your example...

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.