user3458716 user3458716 - 7 months ago 32
Java Question

Replace quotes which are not inside word

I have a long string containing several words.

Some of these words have apostrophe for eg . don't . some words have apostrophe outside the words for example '''movieis great ''' or ''lot of apostrophe ''''' .

I want to remove all the apostrophe that is not a part of the word.

For example in the string = don't try to ''''remove apostr inside'''' word'.
the output should be don't try to remove apostr inside word.

I wrote the regex for it .*[^a-z]'[^a-z].* But I am not getting the desired output in my java code.

String s = "don't try to ''''remove apostr inside'''' word'";
s = s.replace(".*[^a-z]'[^a-z].*", " ");


Note that .replace() only replaces literal strings and does not allow regex as the search argument.

You may use a regex that will match apostrophes not enclosed with word boundaries:

String s = "don't try to ''''remove apostr inside'''' word' 'żoł'";
s = s.replaceAll("(?U)\\B'\\b|\\b'\\B|\\B'\\B", "");

See the online Java demo

Here, \b is a word boundary, \B a position other than word boundary and (?U) makes the \b and \B Unicode aware.