python - replace string via re.sub() using a regular exression as replacer -
string = "@ablue , @red , @gyellow, @yellow, @ggreen" new = re.sub('(@[a-z][a-z])', "########" , string)
i need regular look able check @ next 2 uppercase letters , remove @ , first uppercase character.cc
using capturing grouping , backreference:
>>> import re >>> string = "@ablue , @red , @gyellow, @yellow, @ggreen" >>> re.sub('@[a-z]([a-z])', r"\1" , string) 'blue , @red , yellow, @yellow, green' \1 in substitution string replaced first capturing grouping (the sec uppercase letter).
note used r"raw string literal". otherwise, need escape \: "\\1"
alternative using positive lookahead assertion:
>>> re.sub('@[a-z](?=[a-z])', '' , string) 'blue , @red , yellow, @yellow, green' python regex string
No comments:
Post a Comment