Match at the beggining OR after whitespace with square bracket, r'[^s]+word'

Question:

None these three matches

m = re.search(r'[^s]+ss', "aa ss")
m = re.search(r'[^s]+ss', "ss")
m = re.search(r'[^s]+ss', " ss")

But this matches

m = re.search(r'[s^]+ss', " ss") 

What’s the usually way to match the word "ss" at the beginning or after one or more white-space in a string?

Asked By: LShi

||

Answers:

If I understood it correctly, you can match on the start of the line or a whitespace using |:

(?:^|s)ss
  • (?: – start of non-capturing group
    • ^|s – match on the beginning of the line or a whitespace
  • ) – end of non-capturing group
  • ss – match on literal ss

Demo

In your try:

  • [^s] will match exactly one character that is not a whitespace. [^...] makes the character group negated so that non of the characters in the group is allowed.
  • [s^] will match exactly one character that is either a whitespace or a literal ^ (not the start of the string).
Answered By: Ted Lyngmo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.