Reputation: 455
How can I read an email address as a token?
I saw that the tokenizer method has a limit of 16 bits of length, well my token is like this:
command [email protected] 50
I want to be able to store the email (can be any email address) and the number (can vary from 5-1500). I dont care about the command token.
My code looks like this:
String test2 = command.substring(7);
StringTokenizer st = new StringTokenizer(test2);
String email = st.nextToken();
String amount = st.nextToken();
Upvotes: 1
Views: 1025
Reputation: 120526
StringTokenizer
is not the tool for the job here. Emails are just too complex for it to handle since it is not going to be able to treat valid email addresses where the local-part is a quoted-string as one token:
"foo bar"@example.com
Use a parser generator instead. Many have perfectly good RFC 2822 grammars.
For example, http://users.erols.com/blilly/mparse/rfc2822grammar_simplified.txt defines addr-spec
which is the production you want, and you can define a grammatical production for a command, space, addr-spec, space, number and then define your top level production as a series of those separated by line-breaks.
Upvotes: 2
Reputation: 8100
It looks to me like you do have the email address already stored in your email
variable.
package com.so;
import java.util.StringTokenizer;
public class Q8228124 {
public static void main(String... args) {
String input = "command [email protected] 50";
StringTokenizer tokens = new StringTokenizer(input);
System.out.println(tokens.countTokens());
// Your code starts here.
String test2 = input.substring(7);
StringTokenizer st = new StringTokenizer(test2);
String email = st.nextToken();
String amount = st.nextToken();
System.out.println(email);
System.out.println(amount);
}
}
$ java com.so.Q8228124
3
[email protected]
50
Upvotes: 0
Reputation: 23181
So if you have your data in a variable called command
you could simply do:
StringTokenizer st = new StringTokenizer(command);
st.nextToken(); //discard the "command" token since you don't care about it
String email = st.nextToken();
String amount = st.nextToken();
Alternatively, you can use "split" on the string to load it into an array:
String[] tokens = command.split("\w"); //this splits on any whitespace, not just the space
String email = tokens[1];
String amount = tokens[2];
Upvotes: 0
Reputation: 5850
If you are using spaces as separator, why not code like this:
String[] temp =command.split(" ");
String email = temp[1];
String amount = temp[2];
Upvotes: 1