+ 2

[SOLVED] I can't understand why replaceAll() method does not work as I expect.

I just want replace the very last ".com" to "" but I couldn't figure out what is this weird output and why it happens. https://code.sololearn.com/chlhH32EvGjI/?ref=app

27th Dec 2020, 7:44 PM
hamid
hamid - avatar
3 ответов
+ 4
I think replaceAll takes a regex instead of a normal string. So ".com" means any letter and "com" instead of a dot and "com". But if you put two backslashes (two because one backslash makes an escape character) before ".", it does what you want. I also recommend removing only from the end of the string because "hamid.com@sololearn.com" might be a valid email. You can check this out to learn more about regular expressions: https://www.w3schools.com/java/java_regex.asp
27th Dec 2020, 8:04 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 3
While regex is awesome it can also be annoying! .replaceAll() uses a regex match to find and replace any string that matches the pattern. In regex, the charafter "." means any character, so the regex match "dcom" as well as your ".com". To fix this your regex should look like this: "[.]com"
27th Dec 2020, 7:55 PM
Apollo-Roboto
Apollo-Roboto - avatar
+ 3
thank you all both solution worked quite perfect. although I ask a simple short question but I gotta confess that somehow thousands of my questions SOLVED. really thankful guys
27th Dec 2020, 10:02 PM
hamid
hamid - avatar