C++ Regex not matching multiline strings

后端 未结 2 1878
时光说笑
时光说笑 2021-01-13 01:41

I am having problems with C++0x regex when the string Im matching is a multiline string. Here is the code snippet Im trying to use:

std::smatch regMatch;
std         


        
相关标签:
2条回答
  • 2021-01-13 02:13

    You should use regex_search instead of regex_match.

    By the way, why not use (.*) instead of (.*?)?

    0 讨论(0)
  • 2021-01-13 02:17

    The dot . does not match newline characters by default. You can add the switch (?s) to the beginning of the regex to switch on newline matching for the dot:

    (?s)<key>user</key><string>(.*?)</string>
    

    However, I'm not a huge fan of this because not all languages support this in their regex engines. Additionally, there might be another part of your regex pattern involving a dot that you don't want to match newlines. My preferred method is to just use a character set that includes a character class such as \s or \w along with its negated class. It's a pretty straightforward way of telling the regex to match this will match absolutely everything:

    <key>user</key><string>([\w\W]*?)</string>
    

    Maybe I'm misinterpreting how your XML is going to be parsed, but I've got to say that it's a bit odd how you intend to capture a string with the key name "user" that may or may not contain newlines (and other whitespace characters, and all other characters). Are you really okay with a user named

    admin$#* &% '"; _____?

    0 讨论(0)
提交回复
热议问题