democidist
democidist

Reputation: 105

Regex that only returns True on an absolutely blank line without whitespace

I want to use regex to test if a string is either a - followed by some intentional note, or is completely blank without whitespace of any kind.

I tested it on regex101.com but I don't understand how the $ symbol doesn't singlehandedly prevent the \n character from being a match.

How can I adjust my statement to match my expectations? Thank you in advanced.

match(r"^(-.*|)$", "\n") is not None
#returns True

match(r"(^-.*$|^$)", "\n") is not None
#returns True

Upvotes: 0

Views: 70

Answers (2)

Saleem
Saleem

Reputation: 8988

You can try matching non-space character after -

Regex ^\-\S+ will

-a         <-- match
-          <-- no match
-9ddd      <-- match

See https://regex101.com/r/56iMem/1

Upvotes: 0

Aran-Fey
Aran-Fey

Reputation: 43246

The problem is your use of the $ anchor. From the docs:

'$'

Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline.

You have to use \Z instead, which matches only at the end of the string:

>>> re.match(r'^(-.*)?\Z', '\n') is None
True

Or, alternatively, you could drop the anchors and use re.fullmatch:

>>> re.fullmatch(r'(-.*)?', '\n') is None
True

Upvotes: 5

Related Questions