如何使HTML5电子邮件验证正则表达式在C ++中工作? [英] How to make HTML5 email validation regex work in C++?
问题描述
我正在尝试在客户端和服务器端都验证电子邮件。客户端是JavaScript(Web前端)。服务器端是用C ++ 11编写的。
I am trying to validate email both on the client-side and on the server-side. The client-side is JavaScript(web front-end). The server-side is written in C++11.
我用来验证电子邮件的正则表达式由HTML标准提供(此处)[ https://html.spec.whatwg.org/ multipage / input.html#e-mail-state-(type = email)] 。我在这里复制它以供快速参考:
The regex I am using to validate email is provided by the HTML standard (here)[https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type=email)]. I am reproducing it here for quick reference:
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
验证在客户端使用JavaScript。但是使用 std :: regex_match
的服务器端验证失败。
The validation works on the client-side using JavaScript. But the server-side validation using std::regex_match
fails.
以下是用于检查有效电子邮件的C ++代码:
Following is the C++ code to check valid email:
bool is_valid_email(std::string email)
{
// Regex from HTML5 spec.
static std::regex const email_regex {R"(/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/)"};
return std::regex_match(email, email_regex);
}
我在做什么错了?
推荐答案
JavaScript regex文字两端的 /
是 regex分隔符字符,它们不是正则表达式模式的一部分。
The /
at both ends of the JavaScript regex literal are regex delimiter characters, they are not part of a regular expression pattern.
在C ++中,您使用正则或原始字符串文字设置了正则表达式,
In C++, you set the regex using either regular or raw string literals, do you do not need to include regex delimiters into the pattern.
因此,如果您有 const regex = / abc /
JavaScript,您可以使用
So, if you have const regex = /abc/
in JavaScript, you may use
std::regex const regex {R"(abc)"};
在您的情况下,您甚至不需要 ^
在模式的开头, $
在模式的结尾,因为 regex_match
需要完整的字符串匹配:
In your case, you do not even need the ^
at the start and $
at the end of the pattern since regex_match
requires a full string match:
bool is_valid_email(std::string email)
{
// Regex from HTML5 spec.
static std::regex const email_regex {R"([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)"};
return std::regex_match(email, email_regex);
}
此外, /
不是一个特殊的正则表达式元字符,您不需要对其进行转义。
Also, /
is not a special regex metacharacter, you do not need to escape it.
注意由于最新的JavaScript ECMAScript实现支持更多正则表达式功能,就像无限宽的后向命名捕捉组一样,将JavaScript regex模式转换为C ++兼容的regex模式并不总是那么简单。
NOTE Since the latest JavaScript ECMAScript implementations support many more regex feature, like infinite-width lookbehind, named capturing groups, it is not always so straight-forward to convert a JavaScript regex pattern to a C++ compatible regex pattern.
这篇关于如何使HTML5电子邮件验证正则表达式在C ++中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!