Regex sub not working as expected in python

I have the following string:

param = ' average(provider.cpuUtilization.Average) AS ECSCpuUtilization '

I have the following regex to say match as many white spaces before as and after as and the word after:

as_regex = r"\s+as\s+\w+"

I have verified in a regex tester that this matches what I am looking for.

I do the following call:

new_param = re.sub(as_regex, '', param, re.IGNORECASE)

new_param is the same string as before though. It’s driving me crazy. Calling, param, re.IGNORECASE)

returns the string AS ECSCpuUtilization exactly like I want. re.match does not but I don’t think that should matter because re.sub works the same as if I’m not mistaken.

What am I overlooking here? Let me know if there’s any of clarity I can add.

>Solution :

Set the flags with a keyword argument. Flags should actually be passed as the fifth positional argument, not the fourth one. See the re.sub documentation.

new_param = re.sub(as_regex, '', param, flags=re.IGNORECASE) # or re.I

Alternatively, you can use (?i) in the regular expression itself to ignore case.

as_regex = r"(?i)\s+as\s+\w+"
new_param = re.sub(as_regex, '', param)

Leave a Reply