Example text : "jhon's email address is jhon@gmail.com"
I got an error when identifying jhon's email address from regex.I'm new for this regex so like to have your valuable answers .Thanks in advance Expected result : jhon@gmail.com
Example text : "jhon's email address is jhon@gmail.com"
I got an error when identifying jhon's email address from regex.I'm new for this regex so like to have your valuable answers .Thanks in advance Expected result : jhon@gmail.com
EmailRegex shares the regex for an email address in multiple programming languages. Here are two examples:
Java:
/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i
C#:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
To use the regex, look at the C# and Java documentation or an Java example / C# example
Assuming that your email is separated by white spaces and has '@' in the middle
public static void Main()
{
string text = "There is an email@email.com address in this string";
int indexOfAt = text.IndexOf('@');
int end = text.IndexOf(' ', indexOfAt);
int start = text.LastIndexOf(' ', indexOfAt)+1;
string email = text.Substring(start, end - start);
Console.WriteLine(email);
}
In Java, you would use something like this to find all of the email addresses in a given piece of text:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class EmailAddressMatcher {
public static void main(String[] args) {
String text = "jhon's email address is jhon@gmail.com";
Pattern pattern = Pattern.compile("([a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("found: " + matcher.group(1));
}
}
}
If you want to capture the matched email addresses, simply do that in the while (matcher.find())
loop. Each matcher.group(1)
is an email address found in the text.