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 fnmatch.fnmatch("[seq]") escape not working

According to the https://bugs.python.org/issue13929, "[seq]" should be escaped by the backslash. However, when i run the same code, i have different result like bellow

enter image description here

I need to detect the string contains the "[" and "]". So, my solution is to change "[seq]" to the "{seq}" on both string and pattern like bellow.

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

string = string.replace("[", "{").replace("]", "}")
pattern = pattern.replace("[", "{").replace("]", "}")
fnmatch.fnmatch(string, pattern)

Could there be a better solution?

>Solution :

fnmatch does not support escaping with backslashes. Instead, you should enclose special characters in square brackets. From the docs:

For a literal match, wrap the meta-characters in brackets. For example, ‘[?]’ matches the character ‘?’.

pattern = "*[[]Ver.2]*"
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