Java String remove all non numeric characters but keep the decimal separator

Java String remove all non numeric characters but keep the decimal separator

To remove all non-numeric characters from a Java String while keeping the decimal separator, you can use regular expressions and the replaceAll() method. Here's an example of how to achieve this:

public class RemoveNonNumeric { public static void main(String[] args) { String input = "123.45abc6.78xyz"; // Remove all non-numeric characters except the decimal separator (.) String result = input.replaceAll("[^0-9.]", ""); System.out.println("Original String: " + input); System.out.println("String with only numeric characters: " + result); } } 

In this example:

  1. We define the input String containing a mix of numeric and non-numeric characters, including decimal separators.

  2. We use the replaceAll() method with a regular expression pattern [^0-9.]. This pattern matches any character that is not a digit (0-9) or a period (.). The ^ inside the square brackets negates the character class, meaning it matches characters that are not in the specified range.

  3. The replaceAll() method replaces all non-numeric characters (except the decimal separator) with an empty string, effectively removing them.

When you run the code, you will see that the non-numeric characters have been removed, but the decimal separator remains:

Original String: 123.45abc6.78xyz String with only numeric characters: 123.456.78 

This code will work for various input strings that contain numeric values with or without decimal separators and mixed with non-numeric characters.


More Tags

jax-rs web-deployment comparable crud web-component for-xml-path uicollectionviewcell bitwise-operators turtle-graphics json.net

More Java Questions

More Fitness Calculators

More Chemical reactions Calculators

More Gardening and crops Calculators

More Electrochemistry Calculators