-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

2
  • 1
    Do you want to remove whitespace characters in general or only between brackets? Commented Aug 21, 2017 at 12:00
  • Did my solution below solve your problem? Commented Aug 21, 2017 at 18:12

2 Answers 2

0

This should work fine for you.

    String s = "( 10 )";

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

Ouput:

(10)
Sign up to request clarification or add additional context in comments.

2 Comments

There can be many brackets in my string. I want to replace spaces only when bracket contains numbers.
Is it possible for you to provide some more inputs and outputs like you did for ( 10 ) ?
-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 )

2 Comments

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
Please find updated answer and let me know if it answer your question.