java - 正则表达式仅匹配第一次出现
问题描述
有效的电子邮件格式: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
推荐阅读
- apache-spark - Spark:reduceByKey() 的缓慢实现
- reactjs - 组件正在从另一个组件接收道具,并连接到商店以调用操作
- firebase - Firestore 数组联合:INVALID_ARGUMENT:无法将数组值转换为数组值
- python - Python - 多行命令的语法无效
- java - 清理类路径,将来避免此问题的正确方法是什么?
- scala - 通过反射实例化 Scala 类/案例类
- javascript - JavaScript 不运行第一个代码下面的代码(document.get)
- machine-learning - 为什么我们需要将 K 设置为过滤方法中的输入?
- flutter - 找不到正确的提供者
在此之上 - python - 如何依靠 MongoDB 的电机驱动程序?