3

我正在尝试使用我在此处找到的方法替换除 - 和 _ 之外的所有标点符号,但我只能使用发布的使用负前瞻的确切代码来让它工作:

(?!")\\p{punct}

//Java example:

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

我试过:

name = name.replaceAll("(?!_-)\\p{Punct}", ""); // which just replaces all punctuation.

name = name.replaceAll("(?!\_-)\\p{Punct}", ""); // which gives an error.

谢谢。

4

1 回答 1

8

使用字符类减法(并添加+量词以匹配 1 个或多个标点字符的块):

name = name.replaceAll("[\\p{Punct}&&[^_-]]+", "");

请参阅Java 演示

该方法匹配除and之外[\\p{Punct}&&[^_-]]+的类中的任何字符。\p{Punct}_-

您找到的构造也可以使用,但您需要将-and_放入字符类中,然后使用.replaceAll("(?![_-])\\p{Punct}", ""), 或.replaceAll("(?:(?![_-])\\p{Punct})+", "").

于 2016-10-26T15:50:53.863 回答