1

I cannot seem to figure out how to write a regex to match on if all match in python:

  • {'ERROR_CODE': 500}
  • {'ERROR_CODE': 404}
  • {'ERROR_CODE': 501}
  • {'ERROR_CODE': 409}

I need the regex to match {'ERROR_CODE': first, which can be followed be either 5XX OR 4XX, and ending with }

i am able to specify and get it to work, how to make it match on the entire range 400-499 or 500-599.

// python snippet
err_pattern = re.compile("{\'ERROR_CODE\': 500}|{\'ERROR_CODE\': 404}")
if all(err_pattern.match(str(values)) for values in self.set.values()):
    output.append('All are 4XX and 5XX')

Any help would be highly appreciated.

0

2 Answers 2

1

This is one way you could do it:

import re
values = ["{'ERROR_CODE': 500}",
          "{'ERROR_CODE': 404}",
          "{'ERROR_CODE': 501}",
          "{'ERROR_CODE': 409}]"]

err_pattern = re.compile("\{\'ERROR_CODE\': [45]\d{2}\}")

for value in values:
    if err_pattern.match(value):
        output = "All are 4XX and 5XX"
    else:
        output = "Some values are not error codes"
        break

print output
# All are 4XX and 5XX
Sign up to request clarification or add additional context in comments.

Comments

1

how to make it match on the entire range 400-499 or 500-599.

The 4 and 5 are constant, and the second and third number are all 0-9 digits. Therefore you can make a regex like this:

re.compile(r"\{'ERROR_CODE': [45]\d{2}\}")

Which matches number starts with 4 or 5, followed by 2 digits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.