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
Your regex:
[^A-Z]
matches anything which is not an uppercase letter.
Which means any lowercase letter will match too.
You should probably use:
[^A-Za-z]
as a regex instead.
Note also that this will not account for anything other than ASCII. It may, or may not, be what you want.
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
Your regular expression [^A-Z]
is currently only configured to preserve upper-case letters. You could try replacing it with [^A-Za-z]
to keep the lower-case letters too.
This will remove all digits:
firstname1 = firstname1.replaceAll("\\d","");
public static void main(String[] args) {
String address = "34732483dhshdsdhajsa8ejdsdd";
char[] chars = address.toCharArray();
String aString = "";
for (int i = 0; i < chars.length; i++) {
if (!Character.isDigit(chars[i])) {
aString =aString + chars[i];
}
}System.out.println(aString);
}
/*Remove numbers from given specific string*/
public class NewClass6 {
public static void main(String[] args){
String s= "hello647hi74joke";
char[] ch= s.toCharArray();
System.out.println("Result = " + getString(ch));
}
static String getString(char[] ch){
int m = 0;
char[] chr = new char[50];
char[] k = {'0','1','2','3','4','5','6','7','8','9'};
for(int i = 0; i < ch.length; i++){
for(int j = 0; j < k.length; j++){
if(ch[i]==k[j]){
m--;
break;
}
else {
chr[m]=ch[i];
}
}
m++;
}
String st = String.valueOf(chr);
return st;
}
}