Java split with special characters

Osama Jetawe :

I have below code that doing a split for string using <div>\\$\\$PZ\\$\\$</div> and it's not working using the special characters.

public class HelloWorld{

     public class HelloWorld{

     public static void main(String []args){
          String str = "test<div>\\$\\$PZ\\$\\$</div>test"; 
        String[] arrOfStr = str.split("<div>\\$\\$PZ\\$\\$</div>", 2); 
        for (String a : arrOfStr) 
            System.out.println(a);
     }
}

the output os test<div>\$\$PZ\$\$</div>test

it works when I remove the special characters

Can you please help.

andrewjames :

This:

String str = "test<div>\\$\\$PZ\\$\\$</div>test";
String[] arrOfStr = str.split("<div>\\\\\\$\\\\\\$PZ\\\\\\$\\\\\\$</div>", 2);
for (String a : arrOfStr) {
    System.out.println(a);
}

prints:

test
test

EDIT: Why do we need all those backslashes? It's because of how we need to handle String literals representing regex expressions. This page describes the reason with examples. The essence is this:

For a backslash \...

...the pattern to match that would be \\... (to escape the escape)

... but the string literal to create that pattern would have to have one backslash to escape each of the two backslashes: \\\\.

Add to that the original need to also escape the $, that gives us our 6 backslashes in the string representation.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related