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

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.

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

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

re.search(as_regex, 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 re.search 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)
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