Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string gives null result in java

Tags:

java

i am trying very simple splitting. I dont know why it is not working.

String abc= "192.168.120.2";
String[] eachByteabc= abc.split("."); 

When I debug it and see, I get the result that abc contains : 192.168.120.2. But when I do split, it does not give me error but gives me null result. I think, i have made some silly mistake. Can you tell me where I am wrong. What should I do. Thank you in advance.

like image 622
Xylo_matic Avatar asked Apr 10 '26 12:04

Xylo_matic


2 Answers

Try it =):

String[] eachByteabc= abc.split("\\.");
like image 177
Sergey Morozov Avatar answered Apr 13 '26 02:04

Sergey Morozov


You need to escape the ., since it's a regex operator. Change it to:

String[] eachByteabc= abc.split("[.]"); 

Addition, thanks to @sparks:

While this will work, the [] characters in regex are used to annotate a set, so if you are looking for where it might be in a limited series of characters, you should use them.

In this case - use \\. to escape the . character.

like image 25
Konstantin Yovkov Avatar answered Apr 13 '26 01:04

Konstantin Yovkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!