hi i am using tihs code to find words start with e but it is`t work
code
import re
a="bitte gebe eine nummer bein:"
result=re.sub(r"(\s(e).*\s$)","lol",a,count=1)
print(result)
the output i expect
bitte gebe lol nummer bein
CodePudding user response:
$
matches the end of the string/line in regex (Python Documentation). Your regex would only match a word starting with e
that happens to have a space after it and the end of the string right after (for example "eins zwei eine "
would work).
In addition, .*
is greedy and will consume the rest of your string.
You will also need to put spaces around your replacement string for the desired output.
So you want something like this:
import re
a = "bitte gebe eine nummer bein:"
result = re.sub(r"(\s(e)\w \s)", " lol ", a, count=1)
print(result)
\w
will match [a-zA-Z0-9_]
as many as times as possible and will stop at a space to avoid consuming the rest of the string.