dimButTries
dimButTries

Reputation: 878

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

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

Upvotes: 1

Views: 125

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

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

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

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

Upvotes: 1

Related Questions