gpt4 book ai didi

c++ - 如何在 C++ 正则表达式中匹配换行符?

转载 作者:可可西里 更新时间:2023-11-01 18:31:24 28 4
gpt4 key购买 nike

我尝试了以下正则表达式:

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;
}
}

DEMO

我预计正则表达式会完全正确并且会找到该组。但事实并非如此。为什么?如何匹配 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)*

See your updated demo


更新 - 另一个值得一提的想法: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);

See this demo at tio.run

关于c++ - 如何在 C++ 正则表达式中匹配换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33718410/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com