简体   繁体   中英

multiline regex pattern in c++

I need the pattern to support multi-line. The pattern is taken from the users and they are able to include multi-line string as regex pattern.

For example:

std::regex re("^"+CWD+"("+path_delim+"[\\s\\S]*|$)");
if(std::regex_search(file,re)){
    //do something
}

The CWD variable can be a multi-line string.

PS: It would be good if I can work this around with only std::regex , ie I don't want to use any library if it's not lightweight. Also, it needs to be c++11 .

It seems the multi line regex pattern is already supported. All I needed is to sanitize the variable before passing it to the regex constructor. This is the code I am using to sanitize the string to construct a valid regex:

String sanitizeRegexString(const String& s){
    std::regex re(R"([\s\S])");
    return std::regex_replace (s,re,"[$&]",std::regex_constants::format_default);
}

The above function takes a string and wraps all its characters around with [] thus the string is not interpreted as a regex pattern rather it is treated as a fixed string inside the pattern, while other strings concatenated with it (without sanitization) acts as regex pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM