Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex: to match space character or end of string

Tags:

python

regex

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?

like image 292
whi Avatar asked May 13 '13 10:05

whi


People also ask

Which regex matches only a whitespace character in Python?

\s | Matches whitespace characters, which include the \t , \n , \r , and space characters.

How do you match a string with spaces in Python?

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.

How do I match a character except space in regex?

You can match a space character with just the space character; [^ ] matches anything but a space character.

How do you match a space in regex?

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).


1 Answers

\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.

like image 80
kampu Avatar answered Oct 07 '22 03:10

kampu