我在验证国际电子邮件地址时遇到了一些问题,例如 john.doe@神谕.com
、sara.smith@神谕.com
、babu .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/