You need to use Lookaround that matches but don't include it the match.
(?<=\||^)[a-z]+@[0-9]+(?=\||$)
Here is regex101 online demo
Sample code:
String pattern = "(?i)(?<=\\||^)[a-z]+@[0-9]+(?=\\||$)";
String str = "|ABC@123|abc@123456|ABcD@12";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group());
}
output:
ABC@123
abc@123456
ABcD@12
Lookahead
and lookbehind
, collectively called lookaround
, are zero-length assertions. The difference is that lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. That is why they are called "assertions".
Read more...
Pattern explanation:
(?<= look behind to see if there is:
\| '|'
| OR
^ the beginning of the line
) end of look-behind
[a-z]+ any character of: 'a' to 'z' (1 or more times)
@ '@'
[0-9]+ any character of: '0' to '9' (1 or more times)
(?= look ahead to see if there is:
\| '|'
| OR
$ the end of the line
) end of look-ahead