简体   繁体   中英

How to remove front and end character of a string

For this input : |PS D#W ||OOOP #||# || QQWQ| |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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM