Wang Nick
Wang Nick

Reputation: 495

Tried to remove apostrophes from String in Java

I was trying to replace all apostrophes which were not surrounded by letters with a whitespace. For cases like it's, the apostrophe would not be replaced.

I have tried this:

str.replaceAll("[^a-zA-Z](')", " ")
   .replaceAll("(')[^a-zA-Z]", " ");

However, there was still some cases that could not work, and I also believed there should be a more elegant way to do that. Could someone please help me?

Upvotes: 1

Views: 541

Answers (1)

Whothehellisthat
Whothehellisthat

Reputation: 2152

Regex: ^'+|'+(?!\S) (flags: g, m)

Matches an apostrophe at the start of the input. Matches all apostrophes without a non-whitespace character coming after it. The + allows the previous token (') to be repeated if possible.

If you have examples of apostrophes that are replaced by this but shouldn't be, just leave them in a comment and I'll see if I can amend.

Upvotes: 1

Related Questions