C++ regex_match如何設(shè)置匹配模式

c++
小樊
100
2024-07-17 15:34:52
欄目: 編程語言

在C++中,可以使用regex_match函數(shù)來進(jìn)行正則表達(dá)式匹配。要設(shè)置匹配模式,可以使用std::regex_constants::match_flag_type參數(shù)來指定匹配選項(xiàng)。

以下是一些常用的匹配選項(xiàng):

  1. std::regex_constants::match_default:默認(rèn)的匹配選項(xiàng),不做任何特殊設(shè)置。
  2. std::regex_constants::match_not_bol:不匹配字符串的開頭。
  3. std::regex_constants::match_not_eol:不匹配字符串的結(jié)尾。
  4. std::regex_constants::match_not_bow:不匹配單詞的開頭。
  5. std::regex_constants::match_not_eow:不匹配單詞的結(jié)尾。
  6. std::regex_constants::match_any:匹配任意部分。
  7. std::regex_constants::match_not_null:不匹配空字符串。

例如,以下是一個(gè)使用regex_match函數(shù)并設(shè)置匹配模式的示例:

#include <iostream>
#include <regex>

int main() {
    std::string str = "Hello World";
    std::regex pattern("Hello");

    std::smatch match;
    if (std::regex_match(str, match, pattern, std::regex_constants::match_not_bol)) {
        std::cout << "Match found!" << std::endl;
    } else {
        std::cout << "No match found." << std::endl;
    }

    return 0;
}

上面的示例中,我們使用std::regex_constants::match_not_bol選項(xiàng)來指定不匹配字符串的開頭。如果字符串不以"Hello"開頭,則不會(huì)輸出"Match found!"。

0