removing empty lines using java regex
I have an interesting string I want to properly break up into a string array. This string is as follows.
String test="?[32,120],x1y1,[object pieceP1],null]";
Now I have this regular expression to attack this.
String delims = "[?,\\[\\]]";
Now the results of splitting it using this code
String[] tokens = mapString.split(delims);
yields this result
-->开发者_如何学编程
--> 32 120 --> x1y1 --> object pieceP1 --> nullwhere the arrows are the empty lines.
How can I modify this regular expression so that there are no empty lines?
Thank you greatly in advance.
~ Selcuk
String delims = "[?,\\[\\]]+";
// []+
see the Greedy quantifiers part in Summary of regular-expression constructs of Pattern
but the leading empty element is still there.
You could use Google Guava's Splitter
class to facilitate that: http://guava-libraries.googlecode.com/svn/tags/release09/javadoc/com/google/common/base/Splitter.html
Splitter.omitEmptyStrings()
should do the work.
Try this
public class Regex
{
public static void main(String[] args)
{
String []split = "?[32,120],x1y1,[object pieceP1],null]".split("([?,\\[\\]])+");
for (int i = 0; i < split.length; i++) {
System.out.println("'"+split[i]+"'");
}
}
}
If your test string starts with a delimiter then the index 0 of the array will always be an empty string. You can put a check for it like this if(split[0].length == 0) continue;
>>Output
''
'32'
'120'
'x1y1'
'object pieceP1'
'null'
精彩评论