Click to See Complete Forum and Search --> : Feeling like an idiot (String splitting)


kevinnichols78
April 19th, 2005, 05:17 PM
So I looked at this post here:
http://www.codeguru.com/forum/showthread.php?t=273282&highlight=regular+expressions

Which told me exactly what to do, and if I duplicate exactly what is on that page, it works. However, when I try and make it work for what I want to do, it doesn't. I'm trying to split an IP. It is passed in as a string, so I don't see what the problem is. If I try: ip.split(".") it doesn't seem to work. Can I not split on the period? If I replace the periods and try this: ip.split("#") it works just fine. Any suggestions?

Thank you,
Kevin

dlorde
April 19th, 2005, 06:29 PM
The '.' (period) is a meta-character in regular expressions, it has a special meaning. If you want it just to mean '.' you have to precede it with a backslash (known as 'escaping' it).

See the Regular Expressions Tutorial - Metacharacters (http://java.sun.com/docs/books/tutorial/extra/regex/literals.html).

Mistakes are the portals of discovery...
James Joyce

kevinnichols78
April 19th, 2005, 06:35 PM
That is what I thought...and I tried that...and it gave me this error:

illegal escape character

aznium
April 19th, 2005, 08:15 PM
i never used the split func before...but i like string tokenizers



import java.util.*;

//class...method...etc
String ip = "255.255.255.0";
StringTokenizer st = new StringTokenizer(ip, ".");
int a = st.nextToken();
int b = st.nextToken();
int c = st.nextToken();
int d = st.nextToken();


i havent compiled the code...but it should work ;)

kevinnichols78
April 19th, 2005, 09:18 PM
I think that will solve my problem. Thanks!

Kevin

cma
April 19th, 2005, 09:56 PM
Using StringTokenizer should be considered deprecated. Using String.split() can be a little tricky, in your case, you need two backslash's:

String numericIPAddress = "127.0.0.1";
String[] numericIPOctets = numericIPAddress.split("\\.");

for (String octet : numericIPOctets )
System.out.println(octet);