How to replace all numbers in java string
60,703
Solution 1
The correct RegEx for selecting all numbers would be just [0-9]
, you can skip the +
, since you use replaceAll
.
However, your usage of replaceAll
is wrong, it's defined as follows: replaceAll(String regex, String replacement)
. The correct code in your example would be: replaceAll("[0-9]", "")
.
Solution 2
You can use the following regex: \d
for representing numbers. In the regex that you use, you have a ^
which will check for any characters other than the charset 0-9
String s="ram123";
System.out.println(s);
/* You don't need the + because you are using the replaceAll method */
s = s.replaceAll("\\d", ""); // or you can also use [0-9]
System.out.println(s);
Solution 3
To remove the numbers, following code will do the trick.
stringname.replaceAll("[0-9]","");
Related videos on Youtube

Author by
skyshine
Updated on May 13, 2020Comments
-
skyshine about 3 years
I have string like this String
s="ram123",d="ram varma656887"
I want string like ram and ram varma so how to seperate string from combined string I am trying using regex but it is not workingPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor .getColumnName(1))).replaceAll("[^0-9]+"));
-
Arun Avanathan over 1 yearWhat about consecutive occurrences of numbers? If the example is
string1234value5678
. Wouldn't\\d+
replace it tostringvalue
in two iterations, instead of replacing it 8 times with\\d
?