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

前端 未结 2 1402
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 08:14

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
         


        
相关标签:
2条回答
  • 2021-01-25 09:02

    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", "");
    
    0 讨论(0)
  • 2021-01-25 09:13

    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.

    0 讨论(0)
提交回复
热议问题