java.util.regex.PatternSyntaxException:索引 0 附近未关闭的字符类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24465134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:21:54  来源:igfitidea点击:

java.util.regex.PatternSyntaxException: Unclosed character class near index 0

java

提问by

I am trying to replace all square brackets i my string .

我正在尝试替换我的字符串中的所有方括号。

This is my program

这是我的程序

   package com;

import java.util.ArrayList;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;

public class Teste {

    /**
     * @param args
     * @throws JSONException 
     */
    public static void main(String[] args) throws JSONException {


        String str = "[Fountain#Apple#Big(7)]";

        str.replaceAll("[", "").replace("]", "");

        System.out.println(str);

    }

}

But i am getting

但我得到

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 0
[
^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.clazz(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)
    at java.util.regex.Pattern.expr(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
    at com.Teste.main(Teste.java:19)

Could anybody please tell me how to replace all square brackets ??

谁能告诉我如何替换所有方括号?

采纳答案by Jon Skeet

String.replaceAlltakes a regular expression pattern, but you don't need regular expressions at all. You can use:

String.replaceAll采用正则表达式模式,但您根本不需要正则表达式。您可以使用:

str = str.replace("[", "").replace("]", "");

Or you coulduse a regex if you wanted, replacing both in one go:

或者,您可以根据需要使用正则表达式,一次性替换两者:

str = str.replaceAll("[\[\]]", "");

That's saying "replace any character in the set (open square bracket, close square bracket) with the empty string. The \\is to escape the square brackets within the set.

这就是说“用空字符串替换集合中的任何字符(左方括号,右方括号)。这\\是对集合中的方括号进行转义。

Note that you need to use the result of replace(or replaceAll) - strings are immutable in Java, so any methods like replacedon't modify the existingstring, they return a reference to a newstring with the relevant modifications.

请注意,您需要使用replace(or replaceAll)的结果- 字符串在 Java 中是不可变的,因此任何方法replace都不会修改现有字符串,它们返回对具有相关修改的字符串的引用。