Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - Java: replaceAll doesn't work well with backslash?

I'm trying to replace the beginning of a string with backslashes to something else. For some weird reason the replaceAll function doesn't like backslashes.

String jarPath = "\\xyz\abc\wtf\lame";
jarPath = jarPath.replaceAll("\\xyz\abc", "z:");

What should I do to solve this issue.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Its doesn't like it because is the escape character in C like languages (even as an escape on this forum) Which makes it a poor choice for a file seperator but its a change they introduced in MS-DOS...

The problem you have is that you have escape the twice so \hostpath becomes \\host\path in the string but for the regex has to be escaped again :P \\\\host\\path

If you can use a forward slash this is much simpler

String jarPath = "//xyz/abc/wtf/lame/";
jarPath = jarPath.replaceAll("//xyz/abc", "z:");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...