Nov 21, 2020 at 10:52pm Nov 21, 2020 at 10:52pm UTC
Q: highlight (or determine)the email address from the string using function.
ex: input(from the console) : hgg gcgchj jkvvhc oliver@gmail.com igvjbkn gvjkh
output: oliver@gmail.com
i'm guessing i need to use regex here? could you please explain how to properly do it?
i started something but i guess it's pointless
1 2 3 4 5 6 7 8 9
#include <regex>
#include <iostream>
#include <string>
using namespace std;
double it_is_email(double string, double email) {
const regex pattern
("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+" );
Last edited on Nov 21, 2020 at 10:53pm Nov 21, 2020 at 10:53pm UTC
Nov 22, 2020 at 5:08am Nov 22, 2020 at 5:08am UTC
A regular expression that matches as per RFC 5322 would be horrendously complex.
Here is a simplified version that would match most real-life email addresses.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <string>
#include <regex>
std::string get_email_address( const std::string& str )
{
// somewhat simplified regex for email address (does not handle al edge cases)
// valid characters in the address (anything other than @, space, tab, line feed, new line)
static const std::string valid_char = "[^@ \\t\\r\\n]" ;
static const std::string vcs = valid_char + '+' ; // sequence of one or more valid chars
// simple email address of the form xxxx@yyyy.zzz
static const std::regex email_addr_re( vcs + '@' + vcs + "\\." + vcs );
std::smatch match ;
// if a match for an email address pattern is found, return the found address
if ( std::regex_search( str, match, email_addr_re ) ) return match[0] ;
else return {} ; // no match, return an empty string
}
// simple test driver
int main()
{
const std::string test_str = "hgg gcgchj jkvvhc oliver@gmail.com igvjbkn gvjkh" ;
const std::string email = get_email_address( test_str ) ;
if ( !email.empty() ) std::cout << "found email address '" << email << "'\n" ;
}
http://coliru.stacked-crooked.com/a/63f85c4cbe70857e
Last edited on Nov 22, 2020 at 5:18am Nov 22, 2020 at 5:18am UTC
Nov 22, 2020 at 7:28am Nov 22, 2020 at 7:28am UTC
thank you guys so much :)
Nov 22, 2020 at 11:24am Nov 22, 2020 at 11:24am UTC
Also:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <string>
#include <algorithm>
#include <iostream>
#include <iterator>
std::string get_email_address(const std::string& str)
{
const auto fndat {std::find(str.cbegin(), str.cend(), '@' )};
return std::string(std::find(std::reverse_iterator<decltype (str.cbegin())>(fndat), str.crend(), ' ' ).base(), std::find(fndat + 1, str.cend(), ' ' ));
}
int main()
{
const std::string test_str {"hgg gcgchj jkvvhc oliver@gmail.com igvjbkn gvjkh" };
std::cout << get_email_address(test_str) << '\n' ;
}
Last edited on Nov 22, 2020 at 11:35am Nov 22, 2020 at 11:35am UTC