有效电子邮件格式: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
最佳答案
您没有添加空格来分隔电子邮件。
按如下方式进行:
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
关于java - 正则表达式仅匹配第一次出现的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61172859/