c++ - 使用 Regex 在 C++ 中进行国际电子邮件验证

标签 c++ regex

我在验证国际电子邮件地址时遇到了一些问题,例如 john.doe@神谕.comsara.smith@神谕.combabu .ratnakar+आଆఉఊګ神谕@gmail.com, testæœö.神谕#$&*éùôß@äßæçëêùé+आଆ神谕.com 在 C++ 中使用 REGEX

以下 Regex 在 Java 中对我来说效果很好:

^[\\p{L}0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?$

我尝试在 C++ 中使用相同的方法并稍作修改

std::string str("[\\\\p{L}0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[\\\\p{L}0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\\\p{L}0-9](?:[\\\\p{L}0-9-]*[\\\\p{L}0-9])?\.)+[\\\\p{L}0-9](?:[\\\\p{L}0-9-]*[\\\\p{L}0-9])?"); 

std::regex rx4(str);

但是 regex_match 在所有情况下都失败了。我认为问题在于 \p{L}。当我用 a-z 替换它时,它接受带有英文字母的电子邮件地址。即这个正在工作:

std::regex rx3("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", std::regex::ECMAScript);

/p{L} 来匹配 unicode 字母在 C++ 中不起作用?

最佳答案

C++ std::regex supports 6 regex flavors :

Six different regular expression flavors or grammars are defined in std::regex_constants:

ECMAScript: Similar to JavaScript
basic: Similar to POSIX BRE.
extended: Similar to POSIX ERE.
grep: Same as basic, with the addition of treating line feeds as alternation operators.
egrep: Same as extended, with the addition of treating line feeds as alternation operators.
awk: Same as extended, with the addition of supporting common escapes for non-printable characters.

这些都不支持 Unicode 属性(或 Unicode 类别类),例如 \p{L},因此您不能使用 \p{L} 在你的模式中。

如果适合您,请使用您的解决方法:

std::regex rx3("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", std::regex::ECMAScript);

或者来自 known Validate email address in JavaScript? SO post 的版本(删除 anchor ,因为您正在使用 regex_match 并重新转义以用于非原始字符串文字,以及 std::regex::ECMAScript 因为它是默认使用的):

std::regex rx3("(?:(?:[^<>()\\[\\].,;:\\s@\"]+(?:\\.[^<>()\\[\\].,;:\\s@\"]+)*)|\".+\")@(?:(?:[^<>()‌​\\[\\].,;:\\s@\"]+\\.)+[^<>()\\[\\].,;:\\s@\"]{2,})")

关于c++ - 使用 Regex 在 C++ 中进行国际电子邮件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37961713/

相关文章:

Javascript - 确保输入至少有一个数字

c++ - 我可以使用枚举类值作为可变参数函数的参数吗?

c++ - 您使用了哪些策略来缩短大型项目的构建时间?

c++ - 如何为三元运算符强制斩线?

java - startsWith endsWith 匹配包含正则表达式

sql - PostgreSQL 中的字符串模式匹配

正则表达式直到括号第一次出现为止

正则表达式匹配其中的所有标签文本

c++ - Cpp 预处理器和文件名的基本名称,行号作为字符串

c++ - C+类错误输出