Reputation: 9020
I am having trouble tokenizing or splitting string on the basis of some delimeter. There are two type of Strings that I need to tokenize. Following is the pattern:
a/b/c/d
and
a/b//d
I am confused how to get both parsed by one function. As I cannot judge before parsing that which string is about to be parsed. As the data is dynamic. and I get NoSuchElmenet Exception
when searching for next token if there is not any. Any help is appreciated.
Upvotes: 0
Views: 143
Reputation: 11
If you just want to separate the two patterns or determine which one is which, try with the java Pattern class. Below, a quick solution
String testString = "a/b/c//d";
String checkfor = ".*//.*";
boolean matches = Pattern.matches(checkfor, testString);
The Pattern.matches() will search for the occurrence of two "/" followed by each other and return respectively (e.g "//" and not "/... /").
Good luck
Upvotes: 1
Reputation: 200
I suppose you want to get the tokens {a, b, c, d}
or {a, b, d}
, so, it's very easy using StringTokenizer class.
Look at this example:
String exampleA = "a/b/c/d";
StringTokenizer tokens=new StringTokenizer(exampleA , "/");
while(tokens.hasMoreTokens()){
System.out.println(tokens.nextToken());
}
You'll get:
{a, b, c, d}
And, for the second example:
String exampleB = "a/b//d";
StringTokenizer tokens=new StringTokenizer(exampleB, "/");
while(tokens.hasMoreTokens()){
System.out.println(tokens.nextToken());
}
You'll get:
{a, b, d}
I hope this is useful for you.
Cheers!
Upvotes: 2