【问题标题】:Reading Email Addresses as Tokens将电子邮件地址读取为令牌
【发布时间】:2011-11-22 14:08:24
【问题描述】:

如何读取电子邮件地址作为令牌?

我看到tokenizer方法有16位长度的限制,我的token是这样的:

command emailtest@somewhere.com 50

我希望能够存储电子邮件(可以是任何电子邮件地址)和号码(可以从 5 到 1500 不等)。我不关心命令令牌。

我的代码如下所示:

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

【问题讨论】:

    标签: java token tokenize


    【解决方案1】:

    StringTokenizer 不是这里的工作工具。电子邮件太复杂了,无法处理,因为它无法将本地部分是带引号的字符串的有效电子邮件地址视为一个令牌:

    "foo bar"@example.com
    

    改用解析器生成器。许多都具有非常好的 RFC 2822 语法。

    例如,http://users.erols.com/blilly/mparse/rfc2822grammar_simplified.txt 定义 addr-spec 这是您想要的产生式,您可以为命令、空格、addr-spec、空格、数字定义语法产生式,然后将您的顶级产生式定义为系列由换行符分隔的那些。

    【讨论】:

      【解决方案2】:

      如果您使用空格作为分隔符,为什么不编写这样的代码:

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

      【讨论】:

        【解决方案3】:

        因此,如果您将数据保存在名为 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();
        

        或者,您可以在字符串上使用“split”将其加载到数组中:

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

        【讨论】:

          【解决方案4】:

          在我看来,您的电子邮件地址确实已存储在您的 email 变量中。

          package com.so;
          
          import java.util.StringTokenizer;
          
          public class Q8228124 {
              public static void main(String... args) {
                  String input = "command emailtest@somewhere.com 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
          emailtest@somewhere.com
          50
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-01-30
            • 1970-01-01
            • 2017-05-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多