简体   繁体   English

Java String ReplaceAll方法给出非法重复错误?

[英]Java String ReplaceAll method giving illegal repetition error?

I have a string and when I try to run the replaceAll method, I am getting this strange error: 我有一个字符串,当我尝试运行replaceAll方法时,我收到这个奇怪的错误:

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 {  

How can I replace the occurrences of "{" ? 如何替换"{"的出现?

A { is a regex meta-character used for range repetitions as {min,max} . A {是用于范围重复的正则表达式元字符{min,max} To match a literal { you need to escape it by preceding it with a \\\\ : 要匹配文字{你需要通过在它之前用\\\\来逃避它:

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

If you really intend to replace single characters and not regexes (which is what you seem to want to do here), you should use .replace() , not .replaceAll() . 如果你真的打算替换单个字符而不是正则表达式(这是你似乎想要在这里做的),你应该使用.replace() ,而不是.replaceAll() In spite of its name, .replace() will replace ALL occurrences, not just the first one. 尽管它的名称, .replace()将替换所有出现,而不仅仅是第一次出现。

And in case you wonder, String implements CharSequence , so .replace("{", "\\n") will work. 如果你想知道, String实现了CharSequence ,那么.replace("{", "\\n")将起作用。

Escape it: 逃避它:

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

This is needed since the first argument to replaceAll() is a regular expression , and { has a special meaning in Java regular expressions (it's a repetition operator, hence the error message). 这是必需的,因为replaceAll()的第一个参数是正则表达式{在Java正则表达式中具有特殊含义(它是重复运算符,因此是错误消息)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM