Home > database >  Regex to capture a single character that does not capture all words starting with it
Regex to capture a single character that does not capture all words starting with it

Time:11-15

I cannot make a regex that only captures a trailing space or N of spaces, followed by a single letter s.

((\s) (s){1,1})

Works but breaks when you start to stress test it, for example it greedily captures words beginning with s.

word s word s
word  s
word  suffering
word   spaces
word  s some ss spaces
there's something wrong
words S s 

enter image description here

CodePudding user response:

If you want a single letter s to be captured, as opposed to an s at the beginning of a longer word, you need to specify a word break \b after s:

\s s\b

Demo on regex101

CodePudding user response:

If you for example do not want to match in s# you can also assert a whitespace boundary to the right.

Note that for a match only, you can omit all the capture groups, and using (s){1,1} is the same as (s){1} which by itself can be omitted and would leave just s

\s s(?!\S)

Regex demo

As \s can also match a newline, if you want to match spaces without newlines:

[^\S\n] s(?!\S)

Regex demo

  • Related