Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string on '~|~' separator in Java?

Tags:

java

regex

I have input String '~|~' as the delimiter.

For example: String s = "1~|~Vijay~|~25~|~Pune"; when I am splitting it with '~\\|~' in Java it is working fine.

String sa[] = s.split("~\\|~", -1);
for(String str : sa) {
    System.out.println(str);
}

I am getting the below output.

1
Vijay
25
Pune

When the same program I am running by passing a command-line argument('~\\|~'). It is not properly parsing the string and giving it below output.

1
|
Vijay
|
25
|
Pune

Is anyone else facing the same issue? please comment on this issue.

like image 846
Vijay_Shinde Avatar asked Jan 29 '26 10:01

Vijay_Shinde


1 Answers

You only need a single backslash when running it from the command line. The reason you need two when making the regular expression in Java is that backslash is used to escape the next character in a string literal or start an escape sequence so one backslash is needed to escape the next one in order for it to be interpreted literally.

~\|~
like image 54
Unmitigated Avatar answered Jan 31 '26 23:01

Unmitigated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!