Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remake this python regex produces needed result

I need to remake regex so that it produces needed result

import re

txt = 'aba accca azzza wwwwa accca wwasdwaww abmasedmwa'

regex = re.sub(r'\ba([^a]+)a\b', r'!\1!', txt)
print(regex)

Output:

!b! !ccc! !zzz! wwwwa !ccc! wwasdwaww abmasedmwa

Needed output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a!a a!!!a a!!!a wwwwa a!!!a wwasdwaww abmasedmwa

>Solution :

You can use

import re

txt = 'aba accca azzza wwwwa accca wwasdwaww abmasedmwa'
pattern = r'(?<=\ba)[^\Wa]+(?=a\b)'
print( re.sub(pattern, lambda x: '!' * len(x.group()), txt) )

See the Python demo.

Details

  • (?<=\ba) – a positive lookbehind that matches a location that is immediately preceded with a at the start of a word
  • [^\Wa]+ – one or more word chars other than a
  • (?=a\b) – a positive lookahead that matches a location that is immediately followed with a at the end of a word

Output:

a!a a!!!a a!!!a wwwwa a!!!a wwasdwaww abmasedmwa

The lambda x: '!' * len(x.group()) replacement replaces the match value with the same amount of ! chars.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading