2011-11-22 53 views
1

如何以標記的形式讀取電子郵件地址?將電子郵件地址作爲標記讀取

我看到標記生成器方法具有長度爲16位的限制,以及我的令牌是這樣的:

command [email protected] 50 

我希望能夠存儲電子郵件(可以是任何電子郵件地址)和該數字(可以從5-1500變化)。我不在乎命令令牌。

我的代碼如下所示:

String test2 = command.substring(7); 
StringTokenizer st = new StringTokenizer(test2); 
String email = st.nextToken(); 
String amount = st.nextToken(); 

回答

0

所以,如果你有你的數據在一個名爲command,你可以簡單地做變量:

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(); 

或者,你可以用「分裂」的字符串,將其加載到一個數組:

String[] tokens = command.split("\w"); //this splits on any whitespace, not just the space 
String email = tokens[1]; 
String amount = tokens[2]; 
1

如果使用空格隔開,爲什麼不這樣的代碼:

String[] temp =command.split(" "); 
String email = temp[1]; 
String amount = temp[2]; 
2

StringTokenizer不是這裏的工作工具。電子郵件是太複雜,它來處理,因爲它不會是能夠治療有效的電子郵件地址,在本地部分是帶引號的字符串作爲一個令牌:

"foo bar"@example.com 

使用解析器發電機來代替。許多都有完美的RFC 2822語法。

例如,http://users.erols.com/blilly/mparse/rfc2822grammar_simplified.txt定義了addr-spec這是您想要的生產,您可以爲命令,空間,addr-spec,空格,數字定義語法生產,然後將頂層生產定義爲一系列分離通過換行。

0

它看起來像我有你的電子郵件地址已存儲在你的email變量。

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 
相關問題