6

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?

2
  • @JavaNut13 - thanks!! - and sorry, should have been able to figure that myself! Commented Oct 12, 2015 at 1:19
  • "unlike regex in other languages, i couldn't find an option in Python for everything except whitespace" - oh really? well, you need the same syntax. docs.python.org/2/library/re.html \S is right below \s Commented Oct 12, 2015 at 1:22

2 Answers 2

13

Remember the following:

\s\S
  • \s is whitespace
  • \S is everything but whitespace
Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.