Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create regex to match a string that contains only hexadecimal numbers and arrows?

I am using a string that uses the following characters:

0-9    
a-f    
A-F    
Greater Than, Hyphen

The mixture of the greater than and hyphen must be:

->
-->

Here is the regex that I have so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[0-9a-fA-F\-\>]+

I saw on multiple websites that to have an exclusion(g-zG-Z, other special characters) you would use ^ but I tried to do the following and it did not work:

[^g-zG-Z][0-9a-fA-F\-\>]+
^g-zG-Z[0-9a-fA-F\-\>]+
[0-9a-fA-F\-\>]^g-zG-Z+
[0-9a-fA-F\-\>]+^g-zG-Z
[0-9a-fA-F\-\>]+[^g-zG-Z]

Just to be extra clear since this is a larger question I want my regex to contain:

  • a-z
  • A-Z
  • 0-9
  • Hyphen and Greater than in the order of "->" or "-->"

I test all of the regex using:

import re as regex
regex.match(regex.compile("REGEX"),"String")

Here are some samples:

"0912adbd->12d1829-->218990d"
"ab2c8d-->82a921->193acd7"

>Solution :

Firstly, you don’t need to escape - and >

Here’s the regex that worked for me:
^([0-9a-fA-F]*(->)*(-->)*)*$

Here’s an alternative regex:
^([0-9a-fA-F]*(-+>)*)*$

What does the regex do?

  • ^ matches the beginning of the string and $ matches the ending.
  • * matches 0 or more instances of the preceding token
  • Created a big () capturing group to match any token.
  • [0-9a-fA-F] matches any character that is in the range.
  • (->) and (-->) match only those given instances.

Putting it into a code:

import re
regex = "^([0-9a-fA-F]*(\-\>)*(\-\-\>)*)*$"
re.match(re.compile(regex),"0912adbd->12d1829-->218990d")
re.match(re.compile(regex),"ab2c8d-->82a921->193acd7")
re.match(re.compile(regex),"this-failed->so-->bad")

You can also convert it into a boolean:

print(bool(re.match(re.compile(regex),"0912adbd->12d1829-->218990d")))
print(bool(re.match(re.compile(regex),"ab2c8d-->82a921->193acd7")))
print(bool(re.match(re.compile(regex),"this-failed->so-->bad")))

Output:

True
True
False

I recommend using regexr.com to check your regex.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading