Remove an apostrophe at the beginning or at the end of a word with regex

自作多情 提交于 2020-12-26 23:21:44

问题


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

I want to delete only the apostrophes at the beginning and at the end of the words like this:

apple
orange
banana
joe's

I have tried with the following regex but it doesn't work:

myString.replaceAll("((?<=^)'|'(?=$))", "");

It does not work in IntelliJ:

But it works with regex101.com:

Why the regex dosen't works and how can I remove the beginning and ending apostrophes?

Thank you for your help!


回答1:


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", "");



回答2:


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.



来源:https://stackoverflow.com/questions/43034731/remove-an-apostrophe-at-the-beginning-or-at-the-end-of-a-word-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!