I have a list of String
that contains word. Some words have apostrophe at the beginning or/and at the end like this:
apple
\'orange
banana\'
joe\'s
If you plan to remove single quotes at the start or end of the line, you need to enable multiline mode (e.g. you may do it with an inline modifier (?m)
):
(?m)^'|'$
As ^
and $
are anchors, zero-width assertions, you need no lookarounds to enclose these anchors with.
If you really plan to match '
that are not enclosed with word chars, use a word boundary based solution:
\B'\b|\b'\B
See the regex demo
Details:
\B'\b
- a '
that is preceded with a non-word boundary (there can be start of string or a non-word char immediately before '
) and followed with a word boundary (there must be a word char after '
)|
- or\b'\B
- a '
that is preceded with a word boundary and is followed with a non-word boundary.In Java, do not forget to use double backslashes with \b
and \B
:
myString = myString.replaceAll("\\B'\\b|\\b'\\B", "");
I understand my mistake, I forgot to make the assignment…
myString = myString.replaceAll("(\B'\b)|(\b'\B)", "");
Thank you and sorry for this dumb question.