1

I have a string as follows which can have any number of spaces after the first [ or before the last ]:

my_string = " [  0.53119281  1.53762345  ]"

I have a regular expression which matches and replaces each one individually as follows:

my_regex_start = "(\[\s+)" #Find square bracket and any number of white spaces
replaced_1 = re.sub(my_regex_start, '[', my_string) --> "[0.53119281  -0.16633733  ]"

my_regex_end = "(\s+\])" #Find any number of white spaces and a square bracket
replaced_2 = re.sub(my_regex_end, ']', my_string) -->" [   0.53119281  -0.16633733]"

I have a regular expression which finds one OR the other:

my_regex_both = "(\[\s+)|(\s+\])" ##Find square bracket and any number of white spaces OR ny number of white spaces and a square bracket

How can I use this my_regex_both to replace the first one and OR the second one if any or both are found?

2 Answers 2

2

Instead of catching the brackets, you can replace the spaces that are preceded by [ or followed by ] with an empty string:

import re

my_string = "[  0.53119281  1.53762345  ]"

my_regex_both = r"(?<=\[)\s+|\s+(?=\])"

replaced = re.sub(my_regex_both, '', my_string)

print(replaced)

Output:

[0.53119281  1.53762345]
Sign up to request clarification or add additional context in comments.

Comments

0

Another option you can use aside from MrGeek's answer would be to use a capture group to catch everything between your my_regex_start and my_regex_end like so:

import re

string1 = " [  0.53119281  1.53762345  ]"

result = re.sub(r"(\[\s+)(.*?)(\s+\])", r"[\2]", string1)
print(result)

I have just sandwiched (.*?) between your two expressions. This will lazily catch what is between which can be used with \2

OUTPUT

[0.53119281  1.53762345]

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.