有效的电子邮件格式:word_character@word_character.word_character
..
我尝试过使用(\b\w+\b@\b\w+\b\.\b\w+\b)
正则表达式,但它仅与第一个匹配:
代码:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
Pattern p = Pattern.compile("(\b\w+\b@\b\w+\b\.\b\w+\b)");
String s= "";
while (t-- > 0) {
s += in.next();
}
Matcher m = p.matcher(s);
int count = 0;
while (m.find()) {
count++;
}
System.out.println(count);
}
输入:
1
a1@gmail.com b1@gmail.com c1@gmail.com
Output: 1
Expected output: 3
答案 0 :(得分:2)
您没有在添加空间来分隔电子邮件。
执行以下操作:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many emails do you want to enter?: ");
int t = in.nextInt();
Pattern p = Pattern.compile("(\\b\\w+@\\w+\\.\\w+\\b)");
String s = "";
while (t-- > 0) {
s += in.next() + " "; // Add space here
}
Matcher m = p.matcher(s);
int count = 0;
while (m.find()) {
count++;
}
System.out.println(count);
}
}
示例运行:
How many emails do you want to enter?: 3
a1@gmail.com b1@gmail.com c1@gmail.com
3