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
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