I want to get the string within parentheses from a string with complex parentheses.
Also, parentheses in strings within parentheses are correctly paired.
For example for the input abc[a[12] b[1] * (12 13)] = efg[14]
,
If the request comes in like this, abc[<Answer string>]
In this case <Answer string>
is neither a[12
, nor a[12] b[1
, nor a[12] b[1] * (12 13)] = efg[14
, but a[12] b[1] * (12 13)
.
This question was asked to modify the python code. I added an example I used.
input
self._vars[os.path.basename(b)[:-4]] = nn.Parameter(v, requires_grad=requires_grad)
output
setattr(self, os.path.basename(b)[:-4], nn.Parameter(v, requires_grad=requires_grad))
CodePudding user response:
You can try something like this:
import re
string = 'abc[a[12] b[1] * (12 13)]'
match = re.findall('\[(. )\]', string)
print(match[0])
Output:
a[12] b[1] * (12 13)
Here, \[(. )\]
is matching everything between the outer square brackets.
CodePudding user response:
The idea is to extract everything within the square brackets of the pattern "blah[ ... ] = blah", so you can try the following regex.
The group including parenthesis (. ) matches any number of characters once or more times. The parenthesis control which parts of the string are returned after a match
import re
input = 'abc[a[12] b[1] * (12 13)] = efg[14]'
output = re.findall('\[(. )\] \=', input)
for e in output: #output is a list
print(e)
Output:
a[12] b[1] * (12 13)