-1

I am trying to achieve something like this

Input -> ( 10 )

I want output as (10)

I want to eliminate space between brackets and numbers in Java using String.removeAll(), [Note: Only one space is there]

Unable to write regular expression for this.

I tried:

String s = "( 10 )";
Sysout(s.removeAll("\\( [0-9]+ \\) )" , "\\([0-9]+)"));

But its not working

Assafs
  • 3,257
  • 4
  • 26
  • 39

2 Answers2

0

This should work fine for you.

    String s = "( 10 )";

    s=s.replaceFirst("\\( ", "\\(");
    s=s.replaceFirst(" \\)", "\\)");
    System.out.println(s);

Ouput:

(10)
nagendra547
  • 5,672
  • 3
  • 29
  • 43
  • There can be many brackets in my string. I want to replace spaces only when bracket contains numbers. –  Aug 22 '17 at 05:57
  • Is it possible for you to provide some more inputs and outputs like you did for ( 10 ) ? – nagendra547 Aug 22 '17 at 06:24
-1

Try this

String input="( 10 )";

System.out.println(input.replaceAll("\\(\\s+" , "(").replaceAll("\\s+\\)", ")"));

//replaceAll("\\(\\s+" , "(") --will remove spaces present after (

//replaceAll("\\s+\\)", ")") --will remove spaces present before )

  • my requirements are specific. I want to remove spaces from numbers inside brackets having only single space. There should be no space b/w digits –  Aug 21 '17 at 12:22
  • Please find updated answer and let me know if it answer your question. – Ajay Rajbhar Aug 21 '17 at 13:30