kyrenia
kyrenia

Reputation: 5565

Regex matching except whitespace in Python

I am looking to match on a white space followed by anything except whitespace [i.e. letters, punctuation] at the start of a line in Python. For example:

 ` a`  = True
 ` .` = True
 `  a`  = False    [double whitespace]
 `ab` = False      [no whitespace]

The rule re.match(" \w") works except with punctuation - how do i include that?

Upvotes: 6

Views: 4830

Answers (2)

Sergey
Sergey

Reputation: 341

import re

r = re.compile(r"(?<=^\s)[^\s]+.*")

print r.findall(" a")
print r.findall(" .")
print r.findall("  a")
print r.findall("ab")

output:

['a']
['.']
[]
[]

regex explanation:

  • (?<=^\s) - positive lookbehind, matches whitespace at the beginning of string
  • [^\s]+ - any non whitespace character repeated one or more times
  • .* - any character repeated zero or more times

Upvotes: 1

psla
psla

Reputation: 316

Remember the following:

\s\S
  • \s is whitespace
  • \S is everything but whitespace

Upvotes: 13

Related Questions