简体   繁体   中英

Remove few characters from a string after \\ in java

I want to remove only 5 characters from a string after the occurrence of "\\"(double back slash). For example:-

String s = ":zap:\\ufe0f:umbrella:\\ufe0f:snowflake:\\ufe0f:snowman:\\ufe0f:cyclone:" ;

The output should be :

:zap::umbrella::snowflake::snowman::cyclone:

So, in the above string the 5 letters after the \\ (double back slash) has been removed. How can I achieve this ?

I tried some code but no luck. :(

\️ is an unicode which represents a single character.

This code will remove any character but not of a word character or colon.

String s = ":zap:\ufe0f:umbrella:\ufe0f:snowflake:\ufe0f:snowman:\ufe0f:cyclone:" ;
System.out.println(s.replaceAll("[^\\w:]", ""));

Output:

:zap::umbrella::snowflake::snowman::cyclone:

You can try this Regex "/\\\\.{5}/g" with the replaceAll() method:

String s = ":zap:\ufe0f:umbrella:\ufe0f:snowflake:\ufe0f:snowman:\ufe0f:cyclone:" ;
s=s.replaceAll("/\\.{5}/g", "");

Here is a DEMO of the Regex .

it matches any character exactly 5 times after the \\ .

It gives this output:

:zap:️:umbrella:️:snowflake:️:snowman:️:cyclone:

You can try The working Example here

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