1

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

6
  • 5
    x = '[FacilityID] & " " & [DIAMETER]'? Commented Nov 2, 2017 at 19:46
  • what about \s\&[^&]*$ Commented Nov 2, 2017 at 19:50
  • For the people upvoteing @timgeb I don't understand? It needs to be dynamic, I can't just hardcore the end result in Commented Nov 2, 2017 at 19:52
  • 2
    @TristanForward so why did you not mention that? You explicitly said that you want a string '[FacilityID] & " " & [DIAMETER]'. If you want anything else, you need to specify what characters the brackets can contain. Commented Nov 2, 2017 at 19:53
  • @timgeb Apologies, I thought mentioning using regular expressions to do this was clear will edit it Commented Nov 2, 2017 at 19:56

3 Answers 3

2

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])
Sign up to request clarification or add additional context in comments.

Comments

0

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]'

Comments

0

You could use

\[.+\]
# match [, anything else, backtrack to the first ] found 

Instead of removing everything, you could simply extract the desired output.


In 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]']

See a demo on regex101.com.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.