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:
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 withaat the start of a word[^\Wa]+– one or more word chars other thana(?=a\b)– a positive lookahead that matches a location that is immediately followed withaat 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.