Shuman
Shuman

Reputation: 4132

in python regex How to use * in lookahead assertion?

I have these two string,

s='MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15||guiHelperMenu'

t='MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15|guiHelperMenu'

the only difference is the | and || part at the end of the string, how can I strip the |guiHelperMenu or ||guiHelperMenu part with a regex ? So far I have tried

re.search('^.*(?=\|)',s).group()
'MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15|'

how can I make it support the case where there are two ||? and return 'MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15 in both cases ?

edit: I figured it out two minutes after posting this ... http://rubular.com/r/zcFGLxzfcu

Upvotes: 0

Views: 40

Answers (2)

anubhava
anubhava

Reputation: 785058

You can use this regex for sub:

>>> re.sub(r'\|+[^|]+$', '', s)
'MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15'
>>> re.sub(r'\|+[^|]+$', '', t)
'MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15'

Or using search:

>>> re.search(r'.*?(?=\|+[^|]*$)', s).group()
'MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15'
>>> re.search(r'.*?(?=\|+[^|]*$)', t).group()
'MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15'

To get the last part you can use a capturing group, that will return same string from both the inputs:

>>> re.search(r'\|([^|]+)$', s).group(1)
'guiHelperMenu'
>>> re.search(r'\|([^|]+)$', t).group(1)
'guiHelperMenu'

Or else use a lookbehind regex:

>>> re.search(r'(?<=\|)[^|]+$', s).group()
'guiHelperMenu'
>>> re.search(r'(?<=\|)[^|]+$', t).group()
'guiHelperMenu'

Upvotes: 1

alexanderlukanin13
alexanderlukanin13

Reputation: 4715

If you just want to strip the guiHelperMenu part, you are overdoing it. Just use re.sub:

>>> re.sub('\|+guiHelperMenu$', '', s)
'MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15'
>>> re.sub('\|+guiHelperMenu$', '', t)
'MayaWindow|toolBar2|MainShelfLayout|formLayout14|frameLayout4|formLayout15'

Upvotes: 1

Related Questions