1

I'm trying to get the words between special character '|' which are in format [a-z]+@[0-9]+.

Sample text -

||ABC@123|abc@123456||||||ABcD@12||

Expected output -

ABC@123, abc@123456, ABcD@12

Regex i'm using

(?i)\\|[a-z]+@[0-9]+\\|

When I used this regex, the output i'm getting is |ABC@123|

What mistake I'm doing ? Can somebody help me with this please ?

Sarath
  • 1,438
  • 4
  • 24
  • 40

2 Answers2

3

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
Braj
  • 46,415
  • 5
  • 60
  • 76
0

You should not put the | in your pattern, otherwise it will be matched. Use the lookaraound operators as in the other solution, or just match (demo):

[a-z]+@\d+

You should also consider splitting the string on | as showed here.

Community
  • 1
  • 1
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115