user299709
user299709

Reputation: 5412

python: remove the farthest left instance matching regex

I have a string like

xp = /dir/dir/dir[2]/dir/dir[5]/dir

I want

xp = /dir/dir/dir[2]/dir/dir/dir

xp.replace(r'\[([^]]*)\]', '') removes all the square brackets, I just want to remove the one on the far left.

IT should also completely ignore square brackets with not(random_number_of_characters)

ex /dir/dir/dir[2]/dir/dir[5]/dir[1][not(random_number_of_characters)]

should yield /dir/dir/dir[2]/dir/dir[5]/dir[not(random_number_of_characters)]

ex. /dir/dir/dir[2]/dir/dir[5]/dir[not(random_number_of_characters)]

should yield /dir/dir/dir[2]/dir/dir/dir[not(random_number_of_characters)]

Upvotes: 0

Views: 60

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174786

This code would remove the last square brackets,

>>> import re
>>> xp = "/dir/dir/dir[2]/dir/dir[5]/dir"
>>> m = re.sub(r'\[[^\]]*\](?=[^\[\]]*$)', r'', xp)
>>> m
'/dir/dir/dir[2]/dir/dir/dir'

A lookahead is used to check whether the square brackets are followed by any character not of [, ] symbols zero or more times upto the line end. So it helps to match the last [] brackets. Then replacing the matched brackets with an empty string would completely remove the last brackets.

UPDATE:

You could try the below regex also,

\[[^\]]*\](?=(?:[^\[\]]*\[not\(.*?\)\]$))

DEMO

Upvotes: 2

Braj
Braj

Reputation: 46861

Make it greedy and replace with captured groups.

                   (.*)\[[^]]*\](.*)
 Greedy Group ------^^  ^^^^^^^^-------- Last bracket [ till ] 

Replacement : $1$2 or \1\2

Online demo

sample code:

import re
p = re.compile(ur'(.*)\[[^]]*\](.*)')
test_str = u"xp = /dir/dir/dir[2]/dir/dir[5]/dir"
subst = u"$1$2"

result = re.sub(p, subst, test_str)

Upvotes: 2

Related Questions