Question

If the title not clear, here is the examples

I want to remove all the Special Characters in a String, a word character after special character followed by a white space.

String = "Here is the world's first movie. #movie";

with the above example, I need the output like

"Here is the world first movie movie";

I tried many regex to achieve this, but I can't I tried following

replaceAll("[^\\w]\\w{1}\\s", " ");

but it's not working, can you tell me the Regex for this with explanation.

thanks in advance

Edit: requirement is I want to remove the special character like in #movie, and also want to remove special character with a single character followed by a space like in world's favorite the final output should be world favorite.

MOST PROBABLY THE CHARACTER AFTER A SPECIAL CHARS WILL BE 's'. for example world's, India's, john's

Was it helpful?

Solution 2

Finally I made it to work by many trial and error, The Final Regex String is [^a-zA-Z\\s]s?(\\s)?

str.replaceAll("[^a-zA-Z\\s]s?(\\s)?", "$1");

Here is the Explanation,

[^a-zA-Z\\s]s? => Find all the special character except White space, follwed by one or zero s

(\\s)? => and immediately followed by a one or zero White space.

Here I grouped (\\s) becoz I want to use that in the replaceAll() function as 2nd Parameter to replace as $1.

The Answer is

String orig = "Here is the world's first movie. #movie";`
System.out.println(orig..replaceAll("[^a-zA-Z\\s]s?(\\s)?", "$1"));

Final Output will be Here is the world first movie movie

OTHER TIPS

    String input = "Here is the world's first movie. #movie";
    String output = input.replaceAll("[!@#$%^&*][a-z]+", "");
    System.out.println(output);

Regex - [!@#$%^&*][a-z]+

   [!@#$%^&*] - tests for special character for the first character
   [a-z]+ - tests for word
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top