python_newbie
python_newbie

Reputation: 111

What is the RE to match the list?

I want to know how to construct the regular express to extract the list.

Here is my string:

audit = "{## audit_filter = ['hostname.*','service.*'] ##}"

Here is my expression:

AUDIT_FILTER_RE = r'([.*])'

And here is my search statement:

audit_filter = re.search(AUDIT_FILTER_RE, audit).group(1)

I want to extract everything inside the square brackets including the brackets. '[...]'

Expected Output:

['hostname.*','service.*']

Upvotes: 0

Views: 35

Answers (2)

Emil
Emil

Reputation: 1295

import re
audit = "{## audit_filter = ['hostname.*','service.*'] ##}"
print eval(re.findall(r"\[.*\]", audit)[0]) # ['hostname.*', 'service.*']

findall returns a list of string matches. In your case, there should only be one, so I'm retrieving the string at index 0, which is a string representation of a list. Then, I use eval(...) to convert that string representation of a list to an actual list. Just beware:

  • If there are no matches, ...findall...[0] will throw a list index out of range error
  • Don't use eval() if you ever expect input coming from another source (i.e. input that is not yours) because that would be a security issue.

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

Use r"\[(.*?)\]"

Ex:

import re
audit = "{## audit_filter = ['hostname.*'] ##}"
print(re.findall(r"\[(.*?)\]", audit))

Output:

["'hostname.*'"]

Upvotes: 0

Related Questions