+ 2

Why I obtain Hello123 as a result? And what is the aim of the first argument "a-z"?

System.out.print("Hello123",replace all("a-z",""));

21st Jan 2020, 4:28 PM
Hichem GOUIA
Hichem GOUIA - avatar
9 Answers
+ 2
This is how you should do it- System.out.print("Hello123".replaceAll("[a-z]","")); It is called Regex(Regular expression) and it is used to search or manipulate a string pattern. Here [a-z] is the range of characters which if present in the string are replaced with "".
21st Jan 2020, 4:44 PM
Avinesh
Avinesh - avatar
+ 3
System.out.print("Hello123".replaceAll("[a-z]",""); Here [a-z] is a regex used to find a to z charecters. If found, then it replaced by "". But in question, it is given as a-z only. So if the string "Hello123" contains exactly, then it replaced with "". But the string does not contain the pattern like a-z. So it simply return same....... Try this to see for differece: System.out.print("Helloa-z123".replaceAll("a-z","")); System.out.print("Hello123".replaceAll("a-z",""));
21st Jan 2020, 6:32 PM
Jayakrishna 🇼🇳
+ 1
It will give you an error if you did so and it will not print anything. If you look closely you can see that replaceAll() method that you have declared is not right.
21st Jan 2020, 5:13 PM
Avinesh
Avinesh - avatar
+ 1
Hichem GOUIA Wel come...
21st Jan 2020, 10:13 PM
Jayakrishna 🇼🇳
+ 1
Jayakrishna so it searches for string "a-z" in string "Hello123" not for any lower case letter in [a-z]
22nd Jan 2020, 2:03 PM
Josée Mallah
+ 1
Josée Mallah Yes. If you need search for any lower case letter, then correct statement is System.out.print("Hello123".replaceAll("[a-z]","");
22nd Jan 2020, 2:07 PM
Jayakrishna 🇼🇳
0
So clear thanks But if we put "a-z" instead of "[a-z]" like the example that I found, it replaces nothing!! Why?
21st Jan 2020, 5:07 PM
Hichem GOUIA
Hichem GOUIA - avatar
0
In a challenge question I find it like this System.out.print("hello123", replaceAll("a-z","")); Without [ ] So maybe the question was wrong ...
21st Jan 2020, 5:21 PM
Hichem GOUIA
Hichem GOUIA - avatar
0
Jayakrishna thanks for your explanation 😊
21st Jan 2020, 9:26 PM
Hichem GOUIA
Hichem GOUIA - avatar