You could try:
y = re.findall(r"\(\s*[a-zA-Z]+\s*\)", x)
Where x
is the input.
Note – You will have to import re by using the statement import re
before the program, to use the regex functions
Explanation –
re.findall
is a module that returns an array of the matches found by the regex. The arguments are as follows: regex, string
r"\(\s*[a-zA-Z]+\)"
specifies that the regex is a raw string given by the r
at the start.
\(
means an opening bracket ‘(‘
\s*
means that the opening bracket may be followed by xero-or-more spaces
[a-zA-Z]+
matches the letters inside (one-or-more)
\s*
indicates that the text may be followed by zero-or-more spaces, and then the \)
indicates the closing ‘)’
Edit 1 –
To answer your second doubt in the comments, you could try this:
z = []
for i in y:
str = "(NN " + i[1:]
z.append(str)
print(z)
9
solved Find a single word between two parantences in regexpre python [duplicate]