Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow apostrophe only in words ending with 's

Tags:

regex

php

I'm reading some files and I need to remove all the apostrophes in the strings except the ones in words ending with 's.

Examples:

Frank's blue car -> Frank's blue car

Frank 'blue' car -> Frank blue car

'Frank's blue car -> Frank's blue car

Frank's' blue 'car -> Frank's blue car

'Frank blue car' -> Frank blue car

Frank'blue'car -> Frankbluecar

Thanks in advance for your help!

EDIT: Modified question since I just need the words ending with 's to keep the apostrophe and not only the singular possessive ones.

like image 905
Shaz Avatar asked Dec 08 '25 22:12

Shaz


1 Answers

So basically you want to disallow apostrophes that aren't surrounded by letters on both sides. You can try the following:

/(?<![a-z])'|'(?!s\b)/i

Replace anything that matches that with an empty string. If you want to allow some contractions also, you can broaden it a bit:

/(?<![a-z])'|'(?![a-z]\b)/i

This pattern matches your requirements, but I offer some notes of caution:

  • It will block 'tis and 'twas, which are valid English.
  • The first pattern will block most contractions, such as didn't.
  • Without an English dictionary database, it will be impossible to distinguish between the singular-possessive (e.g. Frank's) and contractions ending in S (e.g. she's).
  • Finally, remember that this will block most plural-possessives as well. This phrase is correct English, but it will still be blocked:

    the kids' toys

like image 82
Justin Morgan Avatar answered Dec 11 '25 13:12

Justin Morgan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!