Regexp to extract data in brackets and commas

So, I have this:

"(ABC, 2004)"

And I will need to extract ABC into a variable, and in 2004 into another. So what I currently have is:

B: re.compile (r '([^)] *,'). findall ("(ABC, 2004)")

Out: ['(ABC,']

+3
source share
2 answers

If your inputs are always like this (starting with "(", end with ")"), you can have your own values ​​like:

input_text.strip(" ()").split(",")

>>> "( ABC,2004 )".strip(" ()").split(",")
['ABC', '2004']

This will use any parentheses at the edges inside the outer brackets.

In addition, if commas can be surrounded / removed by spaces, you can:

[item.strip() for item in input_text.strip(" ()").split(",")]
+5
source

Try just looking for the word characters:

>> re.compile(r'\w+').findall("( ABC,2004 )")
['ABC', '2004']
+2
source

Source: https://habr.com/ru/post/1741583/


All Articles