How to replace all the punctuation except double q

2019-05-24 14:05发布

I am trying to do some string cleanup.

I want to remove all the punctuation from the string except double quotes.

Below trimPunctuation() function works great in removing all the punctuation from the string.

Does anyone know a way to remove all the punctuation but the double quotes.

 private String trimPunctuation( String string, boolean onlyOnce )
    {
        if ( onlyOnce )
        {
            string = string.replaceAll( "\\p{Punct}$", "" );
            string = string.replaceAll( "^\\p{Punct}", "" );
        }
        else
        {
            string = string.replaceAll( "\\p{Punct}+$", "" );
            string = string.replaceAll( "^\\p{Punct}+", "" );
        }
        return string.trim();
    }

More info on Punctuation unicode class can be found here. But, that didn't help me.

1条回答
劫难
2楼-- · 2019-05-24 14:39

You can use a negative lookahead.

(?!")\\p{punct}

Rubular demo

Java example:

String string = ".\"'";
System.out.println(string.replaceAll("(?!\")\\p{Punct}", ""));

查看更多
登录 后发表回答