Reputation: 3524
I have the following string:
x = r"""<FNT size='9'>" & [FacilityID] & " " & [DIAMETER] & "</FNT>"""
Trying dynamically using regular expressions or similar to get final result of :
[FacilityID] & " " & [DIAMETER]
Cannot hardcore the end result.
I have this to remove the from of string up to first [
b = re.sub(r'^.*?\&\s', '', x)
But I can't figure out how to do the reverse to the first ] reading from right to left.
I think i need to use the $ sign but I can't get it to work, thanks
Upvotes: 1
Views: 173
Reputation: 43199
You could use
\[.+\]
# match [, anything else, backtrack to the first ] found
Instead of removing everything, you could simply extract the desired output.
Python
:
import re
string = """
<FNT size='9'>" & [FacilityID] & " " & [DIAMETER] & "</FNT>
<FNT size='9'>" & [anything else] & " " & [something here] & "</FNT>
"""
rx = re.compile(r'\[.+\]')
matches = [match.group(0) for match in rx.finditer(string)]
print(matches)
# ['[FacilityID] & " " & [DIAMETER]', '[anything else] & " " & [something here]']
Upvotes: 0
Reputation: 5425
If you really just want the first [
to the last ]
, you don't even need a regular expression, just index
and lastindex
.
x = r"""<FNT size='9'>" & [FacilityID] & " " & [DIAMETER] & "</FNT>"""
open = x.find("[")
close = x.rfind("]")
print(x[open:close + 1])
Upvotes: 2
Reputation: 20434
Search for the first open square bracket
and then get all characters to the next closing square bracket
and then all characters to the final closing square bracket
:
x = r"""<FNT size='9'>" & [FacilityID] & " " & [DIAMETER] & "</FNT>"""
x = re.findall("\[.*?\].*?\]", x)[0]
which modifies x
to:
'[FacilityID] & " " & [DIAMETER]'
Upvotes: 0