使用BufferedReader Java将行拆分为两个字符串

时间:2016-10-19 15:12:20

标签: java bufferedreader

我如何将#34; Dr. Dr. John Doe John@Doe.com"(line_split [0])读入两个单独的字符串(MailEntry中的名称和电子邮件,。该名称具有无限的字词。

ArrayList<MailEntry> Daten = new ArrayList<MailEntry>();

try {
    File file = new File("MailDaten.txt");
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuffer stringBuffer = new StringBuffer();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        String[] line_split = line.split(" ");
        Daten.add(new MailEntry(line_split[0], line_split[5],
                new TimeEntry(line_split[1], line_split[2], line_split[3], line_split[4])));
        stringBuffer.append(line);
        stringBuffer.append("\n");
    }
    fileReader.close();
    System.out.println("Contents of file:");
    System.out.println(stringBuffer.toString());
} catch (IOException e) {
    e.printStackTrace();
}

4 个答案:

答案 0 :(得分:0)

你可以写一个正则表达式来拆分它。您只想分割最后一个空格:

\\s+(?=[^\\s]*$)

    \\s+    - whitspace for 1 or more characters
    (?=  )  - a group that is not included. will not be used up by the split
    [^\\s]* - not whitespace for any amount of characters
    $       - end of line

示例用例:

String test = "Dr. Dr. John Doe John@Doe.com";
String regex = "\\s+(?=[^\\s]*$)";
String[] result = test.split(regex);
System.out.println(result[0]);
System.out.println(result[1]);

打印哪些:

Dr. Dr. John Doe
John@Doe.com

答案 1 :(得分:0)

您可以根据自己的要求使用以下方法 -

  1. 将每个条目拆分为按空格分隔的标记列表。
  2. 迭代thesd代币并检查&#39; @&#39;在每个令牌中。如果存在,请将其复制为电子邮件地址。
  3. Else concatinate token由空格分隔。这会给你起名字。
  4. 希望这能回答您的疑问!欢呼声。

答案 2 :(得分:0)

你可以试试这个Just Executed it

String test = "Dr. Dr. John Doe John@Doe.com";
        int  s = test.split("@")[0].lastIndexOf(" ");
        String s1 = test.substring(0,s);
        String s2 = test.substring(s+1,test.length());
        System.out.println(s1);
        System.out.println(s2);

答案 3 :(得分:0)

您需要收到电子邮件并从实际字符串中减去它。您可以使用split函数或使用indexOf函数。上面显示了拆分功能的使用。您还可以执行以下操作。

  GraphNet<DirectedGraph>  graphNet;
 std::vector<GraphNet<DirectedGraph>> vecGraphs;

上述代码的输出是:

public static void main(final String[] args) {
    final String nameAndMail = "Dr. Dr. John Doe John@Doe.com";
    String name = "";
    String mail = "";
    final String mailPattern = "\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b";
    final Pattern p = Pattern.compile(mailPattern,
            Pattern.CASE_INSENSITIVE);
    final Matcher matcher = p.matcher(nameAndMail);
    final Set<String> mailList = new HashSet<String>(); // If you have multiple emails in the string

    while (matcher.find()) {
        mail = matcher.group();
        // mailList.add(mail);
        name = nameAndMail.substring(0, nameAndMail.indexOf(mail));
    }
    System.out.println("Name is::" + name);
    System.out.println("Mail is::" + mail);
}