作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我尝试了以下正则表达式:
const static char * regex_string = "([a-zA-Z0-9]+).*";
void find_first(const std::string str);
int main(int argc, char ** argv)
{
find_first("0s7fg9078dfg09d78fg097dsfg7sdg\r\nfdfgdfg");
}
void find_first(const std::string str)
{
std::cout << str << std::endl;
std::regex rgx(regex_string);
std::smatch matcher;
if(std::regex_match(str, matcher, rgx))
{
std::cout << "Found : " << matcher.str(0) << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
}
我预计正则表达式会完全正确并且会找到该组。但事实并非如此。为什么?如何匹配 C++ 正则表达式中的换行符?在 Java 中它工作正常。
最佳答案
dot in regex通常匹配换行符以外的任何字符 std::ECMAScript syntax .
.
not newline any character except line terminators (LF, CR, LS, PS).
0s7fg9078dfg09d78fg097dsfg7sdg\r\nfdfgdfg
[a-zA-Z0-9]+ matches until \r ↑___↑ .* would match from here
在许多正则表达式风格中,有一个 dotall 标志可用于使点也匹配换行符。
如果不是,有不同语言的解决方法,例如 [^]
not nothing 或 [\S\s]
任何空格或一个类中的非空白一起导致任何字符,包括 \n
regex_string = "([a-zA-Z0-9]+)[\\S\\s]*";
或者使用可选的换行符:([a-zA-Z0-9]+).*(?:\\r?\\n.*)*
或 ([ a-zA-Z0-9]+)(?:.|\\r?\\n)*
更新 - 另一个值得一提的想法:std::regex::extended
A <period> ( '.' ), when used outside a bracket expression, is an ERE that shall match any character in the supported character set except NUL.
std::regex rgx(regex_string, std::regex::extended);
关于c++ - 如何在 C++ 正则表达式中匹配换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33718410/
我是一名优秀的程序员,十分优秀!