我正在尝试创建#replaceAll正则表达式来排除某些字符。
我尝试了以下
msg.replaceAll("[^\\w~!@#$%^&*()-=_+`[]{}\\|:;'\"<>,./\\]", "");
但这给了我这个错误
INFO Caused by: java.util.regex.PatternSyntaxException: Unclosed character class near index 36
07.09 00:07:24 [Server] INFO [^\w~!@#$%^&*()-=_+`[]{}\|:;'"<>,./\]
07.09 00:07:24 [Server] INFO ^
我尝试过在线搜索,但不知道我在做什么错。
答案 0 :(得分:1)
对于您的正则表达式,您必须在最后一个\\
之前添加]
,并且不要对第一个[
进行转义,并且还需要在之后的-
进行转义将其更改为
[^\w~!@#$%^&*()\-=_+`\[\]{}\|:;'\"<>,./]
在我这边工作正常
msg = msg.replaceAll("[^\\w~!@#$%^&*()\\-=_+`\\[\\]{}\\|:;'\\\"<>,./]", "");
答案 1 :(得分:1)
我的猜测是,也许此表达式可能是理想的,或者接近一个表达式:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class re{
public static void main(String[] args){
final String regex = "[^\\w~!@#$%^&*()=_+`\\[\\]{}|:;'\"<>,.\\\/-]";
final String string = "ábécédééefg";
final String subst = "";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(subst);
System.out.println(result);
}
}
bcdefg
如果您想探索/简化/修改表达式,可以 在右上角的面板上进行了说明 regex101.com。如果您愿意, 也可以在this link中观看它的匹配方式 针对一些样本输入。