문제

A function receives something like this with special sign (,>_$' and Java replaceAll throwns error.


SAMPLE INPUT

I got an error if input something like this:

[ FAILED ] appendtext variable has with System.lineSeparator():

$model_fsdfdsfdsfdsfdsfds->load('fsdfdsfdsfdsfdsfds','dsfsdfsd');
$model_fsdfdsfdsfdsfdsfds->fsdfdsfdsfdsfdsfds->index();

No error if input as:

[ OKAY ] appendtext variable have simple input with System.lineSeparator():

mysomethingmodel
blabla

EXPLANATIONS

appendtext goes into String with other combinations:

String allappend = "Something simple var" + System.lineSeparator() + "\t{" + System.lineSeparator() + appendtext;

Okay. Than it goes into replaceAll with regex and thrown an error:

str_list = rs.replaceAll(regex_newlinebracket, allappend);

regex_newlinebracket is something regex from another function:

    public String RegexPatternsFunction(String types, String function_name)
    {        
    // get a rid of special sign

    String function_name_quoted = Pattern.quote(function_name);


    switch (types) {
        case "newlinebracket":
            return function_name_quoted + "(\\s|\\t|\\n)+[{]";
    }

    return null;
    }

ERRORS

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Illegal group reference

at java.util.regex.Matcher.appendReplacement(Matcher.java:808)
at java.util.regex.Matcher.replaceAll(Matcher.java:906)
at java.lang.String.replaceAll(String.java:2162)

or exactly insider appendReplacement function from Matcher.java:

               // The first number is always a group
                refNum = (int)nextChar - '0';
                if ((refNum < 0)||(refNum > 9))
                    throw new IllegalArgumentException(
                        "Illegal group reference");
                cursor++;

PROBLEM

Using special characters as for the

$model_fsdfdsfdsfdsfdsfds->load('fsdfdsfdsfdsfdsfds','dsfsdfsd');
$model_fsdfdsfdsfdsfdsfds->fsdfdsfdsfdsfdsfds->index();

throwns an error in combination of replaceAll as Regex pattern.

A PROJECT WORKS IF NO SPECIAL SIGN.

I'm using Pattern.quote to escaping special characters in other words it will not works if come input like () and replaceAll using regex.

In C++ Qt, it's works well, in Java not.

Solutions?

도움이 되었습니까?

해결책

It's fine (and necessary) that you use Pattern.quote. But what's causing the actual problem is the replacement string, since it contains $ (which is the relevant referencing-character in replacement strings). Luckily, Java provides you with another quoting function just to make replacement strings safe: Matcher.quoteReplacement()

So just try

allappend = Matcher.quoteReplacement(allappend);
str_list = rs.replaceAll(regex_newlinebracket, allappend);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top