Maya Python: Why doesn't my regex expression work in Maya?

Hi. I have never used regex before and thought it was about time I learned. I’m putting together a little script to automatically create and assign textures to objects.

I’m thinking I want a kind of pattern checking of words, but I get an error when I try to run this.

import re
name = ‘jacket’
type = ‘d
suffix = ‘.jpg’
pat = re.compile(fr’{name}.{type}.{suffix}’)
result = bool(pat.search(‘jacket_shoe_pants_d_.jpg’))

print(result)

The error is on the following line:

pat = re.compile(fr’{name}.{type}.{suffix}’)

It’s just in Maya it complains. Using an online editor produce the correct result

Firstly, there may be some formatting errors in your post, so I’m not sure if we are all seeing the code correctly. (Some of the text is italicized?) Also, when I pasted the code into Maya, the quotes came in as apostrophes, so some more text formatting weirdness.

Depending on your version of Maya, the f-strings may not be supported. Might try formatting the string the old way for testing in Maya.

For clarity, I will translate the formatting of your string to see what we have and why it fails.

jacket.d..jpg  # regex pattern
jacket_shot_pants_d_.jpg  # test string

While I am no expert in regular expressions, there are some things I’m spotting immediately. “.” matches any single character. You need to add a quantifier to allow for more characters to be considered. Between “jacket” and “d”, you need to allow more characters to match with “+”. And if you’re looking to match the “.” literally in “.jpg” you need to escape it with “\”. Furthermore, you may want to force the file extension match to only search the end of the test string with “$” so that you won’t match on “.jpg.exr” for example. And, you could run into “.jpeg” as well, so you can account for that by adding “e*”; the asterisk matches zero or more of the preceding character.

This should work. I grouped the file extension in parentheses. This will match “jacket”<anything>“d”<any single character>".jpg" or “.jpeg”

jacket.+d.(\.jpe*g)$

I would go event further and specify your file name separators. The above regex will match “jacket_shot_pants_dx.jpg” or “jacket_shot_pantedx.jpg” for example.

This might be best:

jacket_.+_d_(\.jpe*g)$

Anyway, try that.

We don’t just need to know that there is an error. We need to know what the error is.
Make sure that you have “Show Traceback” checked in the Maya script editor and give us the whole error.

It looks like you’re trying to use Python 3 formatting. What version of Maya are you using?
One possible guess I have is that you’re trying to use Python 3 string formatting in Python 2.

Ah sorry. Yes, I forgot to mention I’m using Maya 2020 and that, that’s probably the cause.

Yes sorry about the formatting.
Thank you very much. I’ll try it.

your combining raw strings with format strings

the following should work

pat = re.compile(f’{name}.{type}.{suffix}’)

1 Like