首页 > 解决方案 > 正则表达式仅匹配第一次出现

问题描述

有效的电子邮件格式: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

标签: javaregex

解决方案


您没有添加空间来分隔电子邮件。

执行以下操作:

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

推荐阅读