Gus Fring
Gus Fring

Reputation: 46

Regex allow words that have an apostrophe but does not end in a specific letter like "s"

I've been trying to make a regex that contains an apostrophe but doesn't end with a specific letter, like 's' for example.

I haven't had much luck as of yet, I've tried:

([a-z])|(?!s\b)

but that doesn't seem to produce the correct output, not really sure how you would do it.

Thanks for your help!

Upvotes: 0

Views: 545

Answers (2)

The fourth bird
The fourth bird

Reputation: 163457

You can assert a whitespace boundaries at the left and right, and assert that there is no s directly to the left at the end.

(?<!\S)[a-z']+(?!\S)(?<!s)

The pattern matches:

  • (?<!\S) Assert a whitspace boundary to the left
  • [a-z']+ Match 1+ times either a char a-z or '
  • (?!\S)(?<!s) Assert a whitespace boundary to the right, and assert not s to the left

Regex demo

Note that this could also match a standalone '

Upvotes: 0

wjandrea
wjandrea

Reputation: 33097

[a-z']+(?<!s)\b

Explanation:

  • [a-z'] - Any character in the range a-z or an apostrophe
    • + - One or more of the preceding
  • (?<!s) - Previous character is not s
  • \b - Word boundary

Example input:

don't match words ending in s

Matches:

don't
match
ending
in

Try it on regex101

Upvotes: 1

Related Questions