Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: removing numeric values from string

I have suceeded with the help of this community in removing numeric values from user input, however, my code below will only retrieve the alpha characters before the numeric that has been removed:

import java.util.Scanner;  public class Assignment2_A {      public static void main(String[] args) {         Scanner firstname = new Scanner(System.in);         String firstname1 = firstname.next();         firstname1 = firstname1.replaceAll("[^A-Z]","");         System.out.println(firstname1);     } } 

For example if user input = S1234am, I am only getting back: S. How do I retrieve the remaining characters in the string?

like image 809
user2558595 Avatar asked Jul 07 '13 20:07

user2558595


People also ask

How do I remove non digits from a string?

In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.

How do I remove the alphabet from alphanumeric string in Java?

str = str. replaceAll("[^\\d]", ""); You can try this java code in a function by taking the input value and returning the replaced value as per your requirement. Hope this will help you to achieve your requirement.


2 Answers

This will remove all digits:

firstname1 = firstname1.replaceAll("\\d",""); 
like image 116
jlordo Avatar answered Oct 02 '22 19:10

jlordo


You can use:

firstname1 = firstname1.replaceAll("[0-9]",""); 

This will remove all numeric values from String firstName1.

    String firstname1 = "S1234am";     firstname1 = firstname1.replaceAll("[0-9]","");     System.out.println(firstname1);//Prints Sam 
like image 45
Vishal K Avatar answered Oct 02 '22 18:10

Vishal K