EN VI

regex to match comma separated aws regions in python?

2024-03-14 11:30:04
How to regex to match comma separated aws regions in python

String has multiple data and need to find the match and get the value of comma separated aws regions

data = '''
appname=ivr
age=2years
region='us-east-1a,us-east-2a,us-east-1c'
'''

Would like to get the value for region in out put as 'us-east-1a,us-east-2a,us-east-1c'

tried using this regex but it works only for one value without comma

'(af|il|ap|ca|eu|me|sa|us|cn|us-gov|us-iso|us-isob)-(central|north|.       (north(?:east|west))|south|south(?:east|west)|east|west)-\d{1}'

Solution:

You could just add an optional comma on the end of your regex and then make that a repeating group:

pat = r'((?:af|il|ap|ca|eu|me|sa|us|cn|us-gov|us-iso|us-isob)-(?:central|north(?:east|west)?|south(?:east|west)?|east|west)-\d+[a-z]?,?)+'

out = re.search(pat, data)
print(out.group())

Output:

us-east-1a,us-east-2a,us-east-1c
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login