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

python – Regular expression to check if string matches pattern

I need help writing a regular expression to check strings whether they include a pattern like this: [xx.xx] where x can be any integer. (0-9)

Example:

  • Test [12.34] -> true

    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

  • Test [1234] ->false

>Solution :

[0-9]{2} will match only two digits
\. will match one dot, use escape since . means in regex any character

import re
pattern = re.compile("^\[[0-9]{2}\.[0-9]{2}\]$")
print(bool(pattern.match("[12.34]")))#-> True
print(bool(pattern.match("[1234]")))#-> False
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