Sofia
Sofia

Reputation: 456

RegEx to remove punctuation if it is adjacent to letter

I'm working on a Java project and I want to use a RegEx to replace punctuation, specifically only commas and full-stops, that are adjacent to a letter (except o or O). For example in a string like Love. , o.o I only want to remove the full-stop after the word Love and leave the rest (New string: Love , o.o). I tried [A-NP-Za-np-z][.,], but obviously this removes the last letter of the word as well (New string: Lov , o.o). Any ideas?enter image description here

Upvotes: 1

Views: 406

Answers (1)

anubhava
anubhava

Reputation: 785108

You can use a lookbehind assertion:

(?<=[A-NP-Za-np-z])[.,]

(?<=[A-NP-Za-np-z]) will assert if previous character is one of those defined inside [...].

In Java:

txt = txt.replace("(?<=[A-NP-Za-np-z])[.,]", "");

Upvotes: 1

Related Questions