17

I have below String

  string = "Book Your Domain And Get\n \n\n \n \n \n Online Today."
  string = str.replace("\\s","").trim();

which returning

  str = "Book Your Domain And Get     Online Today."

But what is want is

  str = "Book Your Domain And Get Online Today."

I have tried Many Regular Expression and also googled but got no luck. and did't find related question, Please Help, Many Thanks in Advance

Lav patel
  • 205
  • 1
  • 2
  • 7

9 Answers9

52

Use \\s+ instead of \\s as there are two or more consecutive whitespaces in your input.

string = str.replaceAll("\\s+"," ")
Rafi Kamal
  • 4,522
  • 8
  • 36
  • 50
  • 1
    @JayakrishnanPm That will remove all spaces, instead of replacing multiple consecutive spaces with a single space. – Rafi Kamal Apr 20 '17 at 06:41
14

You can use replaceAll which takes a regex as parameter. And it seems like you want to replace multiple spaces with a single space. You can do it like this:

string = str.replaceAll("\\s{2,}"," ");

It will replace 2 or more consecutive whitespaces with a single whitespace.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
4

First get rid of multiple spaces:

String after = before.trim().replaceAll(" +", " ");
0

If you want to just remove the white space between 2 words or characters and not at the end of string then here is the regex that i have used,

        String s = "   N    OR  15  2    ";

    Pattern pattern = Pattern.compile("[a-zA-Z0-9]\\s+[a-zA-Z0-9]", Pattern.CASE_INSENSITIVE); 

    Matcher m = pattern.matcher(s);

        while(m.find()){
        String replacestr = "";


        int i = m.start();
            while(i<m.end()){
                replacestr = replacestr + s.charAt(i);
                i++;
            }

            m = pattern.matcher(s);
        }

        System.out.println(s);

it will only remove the space between characters or words not spaces at the ends and the output is

NOR152

Ömer
  • 188
  • 2
  • 11
0

Eg. to remove space between words in a string:

String example = "Interactive Resource";

System.out.println("Without space string: "+ example.replaceAll("\\s",""));

Output: Without space string: InteractiveResource

0

If you want to print a String without space, just add the argument sep='' to the print function, since this argument's default value is " ".

Omar
  • 1
  • 3
0
//user this for removing all the whitespaces from a given string for example a =" 1 2 3 4"
//output: 1234 
a.replaceAll("\\s", "")
Ali Tamoor
  • 896
  • 12
  • 18
jayee
  • 9
  • 1
0

String s2=" 1 2 3 4 5 "; String after=s2.replace(" ", "");

this work for me

0
String string_a = "AAAA           BBB";
String actualTooltip_3 = string_a.replaceAll("\\s{2,}"," ");
System.out.println(String actualTooltip_3);

OUTPUT will be:AAA BBB

Procrastinator
  • 2,526
  • 30
  • 27
  • 36