I’m a complete noob to regex and I need help with splitting a string. I am inputing the following data
665 11% R 1 908K 388K fg root top
61 1% S 42 152404K 29716K fg system system_server
38 0% S 1 840K 340K fg root /system/bin/qemud
114 0% S 16 120160K 19156K fg radio com.android.phone
which is nothing but your regular top output. What I intend to do is select on entries like
655 11% R 1 fg root top
Now the code which I use to do the following is
while ((inputLine = in.readLine()) != null)
{
String[] segs= inputLine.split("[ ]+");
str[i] = segs[0]+" "+segs[1]+" "+segs[2]+" "+
segs[3]+" "+segs[6]+" "+segs[7]+" "+segs[8];
Log.v("TOP Output", str[i]);
i++; j++;
}
But the problem I face is, that I get on logcat is
java.lang.ArrayIndexOutOfBoundsException
Where am I going wrong, and what could I do different to prevent this. Thanks for helping.
EDIT: After reading the comments I realize i have a couple of empty line in my output. So in such a case how am I supposed to ignore those line. I know I am supposed to match a case, but I am not sure about the expression or syntax!
You don’t need the character class (square brackets). Space is a regular character in regex, so:
Other than that, assuming array indices are there without range checking is bad style and an
ArrayIndexOutOfBoundsExceptionis just what you’ve asked for.Better do it explicitly:
This way it is guaranteed that every line you match fulfills your expectations and every matcher group contains what you expect, too.
Disclaimer: I’m not especially proud of that regex. It’s quite an ugly one, actually, but it illustrates the point that explicit is more reliable and predictable than implicit. And it has the potential to be improved into a version that matches the desired parts even more accurately than a string split ever could.