Reputation: 11
For this input : |PS D#W ||OOOP #||# || QQWQ|
I want to remove first and last pipe from the string by modifying below regex which I have written for any space and special char removal.
str = str.replaceAll("[^a-zA-Z|]","");
Also I want to combine this regex - str.replaceAll("\\|+","|")
(For updating many pipelines in between string to one pipe). Is it possible to combine this to one regex?
Expected output: PSDW|OOOP|QQWQ
Upvotes: 1
Views: 285
Reputation: 159
I won't ask why you want regex to remove first and last pipe (you could check if string starts and ends with pipe and use substring) Remember that regex is heavier than working with strings.
But...to remove first and last you can use
str.replaceAll("^\\|(.*)\\|$","$1")
Explanation here
then the others. Ofcourse it depends how long is string and how often you use this method - but it's shortest answer for so asked question.
Upvotes: 2