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?
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.
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.
This will remove all digits:
firstname1 = firstname1.replaceAll("\\d","");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With