String split() with delimiter "|"

Hi,

I have a string with delimiter of “|” as below.
String a = “SA| CA| FD|MAXI|”

This string need to split and retrieve the first token value (SA). I try to use split(a, “|”)0 ,but it only return me the first alphabet (S)

Anyway I can achieve to have the first token value?

escape the pipe character. it means “or” in regexp. so instead, use something like

a.split(“\\|”);

Thanks… it’s working now.

However when I replace a string with “|” using the following

obj.replace(“@err”,“S\\|”);

I am getting S\| instead of S| (there is a leading space in front of S\| which should not displayed)

.replace() works as follows:

.replace( “regex”, “replacement string” )

A regex argument of | needs to be escaped twice, once to escape the slash for Java and again to escape the | for regex. This is because | is a regex operator, so, to use it as a ‘to look for’ character, it must be escaped.

Conversely, when used in the ‘replacement string’ position, it doesn’t need to be escaped at all because | is not a special character to Java when it appears as a character or string. (| is used in conditional statements, but that’s another topic). The replacement string argument is simply placed in the target string where it matches the regex.