merge two regular expressions

前端 未结 2 1990
[愿得一人]
[愿得一人] 2020-12-20 13:09

I have two regular expressions, one pulling out usernames from a csv string, and the other pulling out emails.

the string format is like this:

String         


        
2条回答
  •  时光取名叫无心
    2020-12-20 13:43

    You can just use an Pipe (|) in between your multiple Regex, to match all of them : -

        String s = "name lastname (username) ; name lastname
                (username) ; name lastname 
                (username) ;";
    
        // Matches (?<=\\()[^\\)]+  or  ((?<=<)[^>]+)
        Pattern pattern = Pattern.compile("(?<=\\()[^\\)]+|((?<=<)[^>]+)");
        Matcher matcher = pattern.matcher(s);
    
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    

    OUTPUT: -

    username
    mail@mail.something.dk
    username
    mail@mail.something.dk
    username
    mail@mail.something.dk
    

    UPDATE: -

    If you want to print username and email only when they both exists, then you need to split your string on ; and then apply the below Regex on each of them.

    Here's the code: -

        String s = "name lastname (username) ; 
                    name lastname (username) ; 
                    name lastname (username) ;";
    
        String [] strArr = s.split(";");
    
        for (String str: strArr) {
    
            Pattern pattern = Pattern.compile("\\(([^\\)]+)(?:\\))\\s(?:\\<)((?<=<)[^>]+)");
            Matcher matcher = pattern.matcher(str);
    
            while (matcher.find()) {
                System.out.print(matcher.group(1) + " " + matcher.group(2));
            }
            System.out.println();
        }
    

    OUTPUT: -

    username mail@mail.something.dk
    username mail@mail.something.dk // Only the last two have both username and email
    

提交回复
热议问题