sTg
sTg

Reputation: 4424

Regex to include multiple EmailIds in Java

I have a requirement where I send multiple emails to client.

But I have a issue while sending email to multiple email Ids.

For example, if I write

[email protected];[email protected]

It would throw me an error stating email id is not correct.

I want the email ids to be separated by semicolon but it seems my regex is not supporting semicolons.

Proper format should be :

[email protected];[email protected]

Should not allow

s;[email protected]

Regex used

myregex = "^['_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"

Please guide.

Upvotes: 3

Views: 431

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

You have a regex for 1 email.

Now, you want to check if the string contains email + ( ; + email ) {any number of times}.

You need to use your previous pattern as a block without anchors and build the final pattern like this:

String myregex = "['_A-Za-z0-9-+]+(?:\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(?:\\.[A-Za-z0-9]+)*\\.[A-Za-z]{2,}"; 
String final_pattern = "\\A" + regex + "(?:;" + regex + ")*" + "\\z";

See the regex demo

Note that \A is the unambiguous start of string and \z - the very end of string anchors.

Also note that the + inside a character class loses its special meaning of a quantifier (1 or more times), and becomes/is treated as a mere literal + symbol. I also removed unnecessary groupings and turned all capturing groups into non-capturing for a "cleaner" matching (if you need no captured values, why store them in a stack for each group?).

Upvotes: 2

SlothProgrammer
SlothProgrammer

Reputation: 1

I think that if you use string.split("_"); you will be fine. I used for mine bodyremoveregex=(ÎÎÎÎΣ On Line)([,]* [0-9]:[0-9], [0-9]/[0-9])*__(/**/) and it worked correctly.You just have to add _ between the expressions.For some reason it doesn't show the _ symbol in my answer so imagine that everywhere I have __ I mean _.

Upvotes: 0

Related Questions