Search code examples
javareplacepattern-matchingreplaceall

Replace all the occurrence of {.?!"><',/\|@#$%^&*~`-_=+} with a word "myWord"


For Example: input String is

Input =  "Hello there, How are you? Fine!! @xyz"

and the output would be

Output = "Hello there myWord How are you myWord Fine myWord myWord  myWord xyz"

i have tried with Pattern class and Matcher class but it only replaces one type of pattern and str.replace(".","myWord");


Solution

  • you can use [^\\w\\s]

    \\s*[^\\w\\s]\\s* :\\s* mean one or more space

    [^\\w\\s] : ^ don't capture \\w and \\s

    \\w mean a-zA-Z0-9_

    \\s mean space


        String s="Hello there, How are you? Fine!! @xyz";
        System.out.println(s.replaceAll("\\s*[^\\w\\s]\\s*", " myWord "));
    

    Output :

    Hello there myWord How are you myWord Fine myWord  myWord  myWord xyz
    

    To avoid any other special character , that shouldn't be replaced then just add them inside this [] e.g \\s*[^\\w\\s:;\\[\\]]\\s* , as pointed by @brso05


    Demo

    const regex = /\s*[^\w\s\]\[;]\s*/g;
    const str = `Hello there, How are you? Fine!! ; @xyz []`;
    const subst = ` myWord `;
    const result = str.replace(regex, subst);
    console.log(result);