Problem solving: java.lang.IllegalArgumentException: character to be escaped is missing

Problem scenario

When building a code generation tool, you need to store the result of the corresponding code under src/test/resources and generate it according to the package path. Wherein the packet path is .replaced directory separator, test code as follows:

import java.io.File;

public class Test {
    
    
    public static void main(String[] args){
    
    
        String packageName = "com.test.aba";
        String path = packageName.replaceAll("\\.", File.separator);
        System.out.println(path);
    }
}

Prompt to report an error, the error message is as follows:

Exception in thread "main" java.lang.IllegalArgumentException: character to be escaped is missing
	at java.util.regex.Matcher.appendReplacement(Matcher.java:809)
	at java.util.regex.Matcher.replaceAll(Matcher.java:955)
	at java.lang.String.replaceAll(String.java:2223)
	at com.gop.yy.api.web.Test.main(Test.java:15)

This blog is mainly about the solution to this problem.

Problem environment

software version
JDK 1.8

problem causes

Under the windows platform, File.separatorthe value \is recognized as an escape character when it is replaced, so the parameter received by the ""method is , so the method reports an error.

solution

To \do the conversion, convert it to a non-escaped character. Here it is necessary to use Matcher.quoteReplacementa method, the method is defined as follows:

java.time.Matcher.quoteReplacement(String s)方法
返回指定String的文字替换String。

参数
s - 要文字化的字符串。

返回值
文字字符串替换。

result

The latest code is as follows:

import java.io.File;

public class Test {
    
    
    public static void main(String[] args){
    
    
        String packageName = "com.test.aba";
        String path = packageName.replaceAll("\\.", Matcher.quoteReplacement(File.separator));
        System.out.println(path);
    }
}

No error is reported during operation.

to sum up

Think more.

Ask for praise

If my article is helpful to everyone, you can click like or favorite at the bottom of the article;
if there is a good discussion, you can leave a message;
if you want to continue to view my future articles, you can click Follow
You can scan the following QR code to follow me 'S public account: Fengye Zhixuege, check out my latest share!
Insert picture description here
Bye bye

Guess you like

Origin blog.csdn.net/u013084266/article/details/115014613