У меня есть такой текст в моем String s (который я уже читал из txt.file)
trump;Donald Trump;[email protected]
obama;Barack Obama;[email protected]
bush;George Bush;[email protected]
clinton,Bill Clinton;[email protected]
Потом пытаюсь отрезать все, кроме адреса электронной почты, и распечатать на консоли
String f1[] = null;
f1=s.split("(.*?);");
for (int i=0;i<f1.length;i++) {
System.out.print(f1[i]);
}
и у меня есть такой вывод:
[email protected]
[email protected]
[email protected]
[email protected]
Как я могу избежать такого вывода, я имею в виду, как я могу получить выходной текст без разрывов строк?
trump @ yahoo.euobama @ google.combush @ inbox.comclinton @ mail.com




Попробуйте использовать нижеприведенный подход. Я прочитал ваш файл с помощью Scanner, а также BufferedReader, и в обоих случаях я не получаю разрыв строки. file.txt - это файл, содержащий текст, и логика разделения остается такой же, как и у вас.
public class CC {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(new File("file.txt"));
while (scan.hasNext()) {
String f1[] = null;
f1 = scan.nextLine().split("(.*?);");
for (int i = 0; i < f1.length; i++) {
System.out.print(f1[i]);
}
}
scan.close();
BufferedReader br = new BufferedReader(new FileReader(new File("file.txt")));
String str = null;
while ((str = br.readLine()) != null) {
String f1[] = null;
f1 = str.split("(.*?);");
for (int i = 0; i < f1.length; i++) {
System.out.print(f1[i]);
}
}
br.close();
}
}
Вы можете просто заменить все прерыватели строк, как показано в приведенном ниже коде:
String f1[] = null;
f1=s.split("(.*?);");
for (int i=0;i<f1.length;i++) {
System.out.print(f1[i].replaceAll("\r", "").replaceAll("\n", ""));
}
Это заменит все их без пробела.
package com.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String s = "trump;Donald Trump;[email protected] "
+ "obama;Barack Obama;[email protected] "
+ "bush;George Bush;[email protected] "
+ "clinton;Bill Clinton;[email protected]";
String spaceStrings[] = s.split("[\\s,;]+");
String output = "";
for(String word:spaceStrings){
if (validate(word)){
output+=word;
}
}
System.out.println(output);
}
public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile(
"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$",
Pattern.CASE_INSENSITIVE);
public static boolean validate(String emailStr) {
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
return matcher.find();
}
}
Вместо разделения вы можете сопоставить формат, подобный электронному письму, сопоставив не точку с запятой или пробельный символ один или несколько раз, используя класс отрицательных символов [^\\s;]+, за которым следует @, и снова сопоставив не точку с запятой или пробельный символ.
final String regex = "[^\\s;]+@[^\\s;]+";
final String string = "trump;Donald Trump;[email protected] \n"
+ " obama;Barack Obama;[email protected] \n"
+ " bush;George Bush;[email protected] \n"
+ " clinton,Bill Clinton;[email protected]";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
final List<String> matches = new ArrayList<String>();
while (matcher.find()) {
matches.add(matcher.group());
}
System.out.println(String.join("", matches));
[^\\s;]+@[^\\s;]+
Просто замените '\ n', которые могут появиться в начале и в конце. напишите так.
String f1[] = null;
f1=s.split("(.*?);");
for (int i=0;i<f1.length;i++) {
f1[i] = f1[i].replace("\n");
System.out.print(f1[i]);
}
Как бы выглядел ваш желаемый результат?