I want to match space chars or end of string in a text.
import re
uname='abc'
assert re.findall('@%s\s*$' % uname, '@'+uname)
assert re.findall('@%s\s*$' % uname, '@'+uname+' '+'aa')
assert not re.findall('@%s\s*$' % uname, '@'+uname+'aa')
The pattern is not right.
How to use python?
\s | Matches whitespace characters, which include the \t , \n , \r , and space characters.
Python String isspace() Method. Python String isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as: ' ' – Space.
You can match a space character with just the space character; [^ ] matches anything but a space character.
If you're looking for a space, that would be " " (one space). If you're looking for one or more, it's " *" (that's two spaces and an asterisk) or " +" (one space and a plus).
\s*$
is incorrect: this matches "zero or more spaces followed by the end of the string", rather than "one or more spaces or the end of the string".
For this situation, I would use
(?:\s+|$)
(inside a raw string, as others have mentioned).
The (?:)
part is just about separating that subexpression so that the | operator matches the correct fragment and no more than the correct fragment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With