How to combine linear break in C ++ regular expression?

I tried the following regex:

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

I expected the regex to be completely correct and the group would be found. But this is not so. What for? How can I combine line breaks in a C ++ regular expression? In Java, it works great.

+7
source share
3 answers

A period in a regular expression usually matches any character except the syntax std :: ECMAScript .

. 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 

Many varieties of regular expressions have a dot flag, so that the dot also matches newlines.

If not, then there are workarounds in different languages, such as [^] , and not nothing, or [\S\s] any spaces or non-spaces together in the class that result in any character, including \n

 regex_string = "([a-zA-Z0-9]+)[\\S\\s]*"; 

Or use optional line breaks: ([a-zA-Z0-9]+).*(?:\\r?\\n.*)* Or ([a-zA-Z0-9]+)(?:.|\\r?\\n)*

Watch the updated demo

+5
source

You can try const static char * regex_string = "((.|\r\n)*)"; Hope this helps you.

+3
source

I use CTest and PASS_REGULAR_EXPRESSION PROPERTIES.

[\ S \ s] * did not work, but (. | \ R | \ n) * did work.

This is a regex:

 Function registered for ID 2 was called(.|\r|\n)*PASS 

Matches:

 Running test function: RegisterThreeDiffItemsTest04 ID 2 registered for callback ID 4 registered for callback ID 11 registered for callback Function registered for ID 2 was called ID 2 callback deregistered ID 4 callback deregistered ID 11 callback deregistered Setup: PASS 

Note. CMakeLists.txt must be escaped from backslash:

 SET (ANDPASS "(.|\\r|\\n)*PASS") 
+1
source

All Articles