Vinoth
Vinoth

Reputation: 123

Reg ex for matching and removing number from a String in java

I am looking forward to remove any number(with decimal) contained within a string.
For Ex:
Input: "The game received average review scores of 96.92% and 98/100 for the Xbox 360 version." Output:- "The game received average review scores of % and / for the Xbox version."

I implemented this on using regex. But, my syntax removes the period at the end of the string as well.

Code:

if(token.matches(".*\\d.*"))  {  
    String s7=token.replaceAll("[0-9,.]", "");  
    s7=s7.replaceAll("( )+", " ");  
    stream.set(s7);  
}

Upvotes: 0

Views: 150

Answers (2)

Paul Vargas
Paul Vargas

Reputation: 42020

Try the regular expression:

\b\d+([.,]\d+)*\b

For an explanation of this regex, see http://rick.measham.id.au/paste/explain.pl?regex=%5Cb%5Cd%2B%28%5B.%2C%5D%5Cd%2B%29*%5Cb.

e.g.:

public static void main(String[] args) {
    String input = "The game received average review scores of 96.92% and 98/100 for the Xbox 360 version.";
    System.out.println(
        input.replaceAll("\\b\\d+([.,]\\d+)*\\b", "")
    );  // prints "The game received average review scores of % and / for the Xbox  version."
}

Upvotes: 1

Rijo Joseph
Rijo Joseph

Reputation: 1405

try this regex (\d|\.)+ ,this will match numbers(including decimal points) then replace the matching group with ""

try this.

 String str="The game received average review scores of 96.92% and 98/100 for the Xbox 360 version";
            Pattern pattern = Pattern.compile("(\d|\.|,)+");
    Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
        str=str.replace(matcher.group(),"");
    }

Upvotes: 0

Related Questions