在JS正则表达式符号中 ^
和 $
指定 字符串的开头和结尾。而且只有 /m
他们匹配的修饰符(多行模式) 开始和结束 - CR / LF前后的位置。
但在 的std ::正则表达式/ ECMAscript模式符号 ^
和 $
比赛 开始和结束 总是。
在std :: regex中有什么方法可以定义 字符串的开头和结尾 赛点?换句话说:支持JavaScript多线模式......
在JS正则表达式符号中 ^
和 $
指定 字符串的开头和结尾。而且只有 /m
他们匹配的修饰符(多行模式) 开始和结束 - CR / LF前后的位置。
但在 的std ::正则表达式/ ECMAscript模式符号 ^
和 $
比赛 开始和结束 总是。
在std :: regex中有什么方法可以定义 字符串的开头和结尾 赛点?换句话说:支持JavaScript多线模式......
默认情况下,ECMAscript模式已经处理 ^
作为两个输入的开始 和 开头的,和 $
作为两个输入结束 和 行结束。没有办法使它们匹配 只要 输入的开头或结尾,但可以使它们匹配 只要 开头或结尾:
调用时 std::regex_match
, std::regex_search
, 要么 std::regex_replace
,有一个类型的论点 std::regex_constants::match_flag_type
默认为 std::regex_constants::match_default
。
^
仅匹配行首,指定 std::regex_constants::match_not_bol
$
仅匹配行尾,指定 std::regex_constants::match_not_eol
std::regex_constants::match_not_bol | std::regex_constants::match_not_eol
)^
而且不管是否存在 std::regex_constants::match_not_bol
通过指定 std::regex_constants::match_continuous
这在很好地解释了 ECMAScript语法文档 上 cppreference.com,我强烈推荐cplusplus.com。
警告:我已经使用MSVC,Clang + libc ++和Clang + libstdc ++进行了测试,目前只有MSVC具有正确的行为。
该 ^
和 $
匹配开头和结尾 串,不是一条线。看到 这个演示 没有找到任何匹配 "1\n2\n3"
同 ^\d+$
正则表达式。添加替换时(见下文), 有3场比赛。
没有选择 std::regex
使锚点匹配线的开始/结束。您需要使用替换来模拟它:
^ -> (^|\n)
$ -> (?=\n|$)
注意 $
可以完全“模仿” (?=\n|$)
(您可以在其中添加更多行终止符号或符号序列,例如 (?=\r?\n|\r|$)
),但有 ^
,你找不到100%的解决方法。
由于没有lookbehind支持,您可能必须调整正则表达式模式的其他部分,因为 (^|\n)
喜欢使用捕获组比使用lookbehind支持更频繁。
以下代码段匹配以[a-z]开头,后跟0或1点,然后是0或更多a-z字母,然后以“@ gmail.com”结尾的电子邮件地址。我测试了它。
string reg = "^[a-z]+\\.*[a-z]*@gmail\\.com$";
regex reg1(reg, regex_constants::icase);
reg1(regex_str, regex_constants::icase);
string email;
cin>>email;
if (regex_search(email, reg1))