java.util.regex.PatternSyntaxException:索引0附近的未闭合字符类 [英] java.util.regex.PatternSyntaxException: Unclosed character class near index 0

查看:174
本文介绍了java.util.regex.PatternSyntaxException:索引0附近的未闭合字符类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的程序

   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);

    }

}

但我是获取

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 ??

推荐答案

String.replaceAll 采用正则表达式模式,但您不需要常规表达式什么都没有。您可以使用:

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

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

或者你可以使用正则表达式,如果你愿意,可以在一个中取代go:

Or you could use 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.

请注意,您需要使用替换(或 replaceAll )的结果 - 字符串在Java中是不可变的,所以任何方法如 replace 不要修改现有的字符串,它们会返回对带有相关修改的 new 字符串的引用。

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

这篇关于java.util.regex.PatternSyntaxException:索引0附近的未闭合字符类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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