Java String ReplaceAll方法给出非法重复错误? [英] Java String ReplaceAll method giving illegal repetition error?

查看:114
本文介绍了Java String ReplaceAll方法给出非法重复错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,当我尝试运行 replaceAll 方法时,我收到了这个奇怪的错误:

I have a string and when I try to run the replaceAll method, I am getting this strange error:

String str = "something { } , op";
str = str.replaceAll("o", "\n"); // it works fine
str = str.replaceAll("{", "\n"); // does not work

我收到一个奇怪的错误:

and i get a strange error:

Exception in thread "main" java.util.regex.PatternSyntaxException:
Illegal repetition {  

如何替换{

推荐答案

{是用于范围重复的正则表达式元字符 {min,max } 。要匹配文字 {,您需要通过前面的 \\ 来逃避它:

A { is a regex meta-character used for range repetitions as {min,max}. To match a literal { you need to escape it by preceding it with a \\:

str = str.replaceAll("\\{", "\n"); // does work

这篇关于Java String ReplaceAll方法给出非法重复错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆