How do I delete the first and last occurrence of the sentence in java

advertisements

I have a following line : |A|B|C|D|100|E|GEN|smsplus|11|11|11| and I want to remove the first and last occurrence of |.

I have to check first if the | is available at first and last

I am sure that this will bring me some down votes but really don't know how to go about.

EDIT

I also have to check for the following :

A|B|C|D|100|E|GEN|smsplus|11|11|11| and |A|B|C|D|100|E|GEN|smsplus|11|11|11 and there is no

possibilities for || that is why I did not want to give any explanation for the same.

thanks for your valuable time.


Your comments lead me to believe that you want to do this:

String result = subject.replaceAll("^\\||\\|$", "");

This will change each of the following strings:

|A|B|C|
|A|B|C
A|B|C|
A|B|C

to the same string A|B|C.

See it on regex101.com.