📜  std :: regex_match,std :: regex_replace()| C++中的正则表达式(正则表达式)

📅  最后修改于: 2021-05-30 18:09:00             🧑  作者: Mango

正则表达式是“正则表达式”的缩写,通常以这种方式在编程语言和许多不同的库中使用。 C++ 11及更高版本的编译器支持它。

正则表达式中使用的函数模板

regex_match() -如果正则表达式与给定字符串匹配,则此函数返回true,否则返回false。

// C++ program to demonstrate working of regex_match()
#include 
#include 
  
using namespace std;
int main()
{
    string a = "GeeksForGeeks";
  
    // Here b is an object of regex (regular expression)
    regex b("(Geek)(.*)"); // Geeks followed by any character
  
    // regex_match function matches string a against regex b
    if ( regex_match(a, b) )
        cout << "String 'a' matches regular expression 'b' \n";
  
    // regex_match function for matching a range in string 
    // against regex b
    if ( regex_match(a.begin(), a.end(), b) )
        cout << "String 'a' matches with regular expression "
                "'b' in the range from 0 to string end\n";
  
    return 0;
}

输出:

String 'a' matches regular expression 'b' 
String 'a' matches with regular expression 'b' in the range from 0 to string end

regex_search() –此函数用于搜索与正则表达式匹配的模式

// C++ program to demonstrate working of regex_search()
#include 
#include 
#include
using namespace std;
  
int main()
{
    // Target sequence
    string s = "I am looking for GeeksForGeeks "
               "articles";
  
    // An object of regex for pattern to be searched
    regex r("Geek[a-zA-Z]+");
  
    // flag type for determining the matching behavior
    // here it is for matches on 'string' objects
    smatch m;
  
    // regex_search() for searching the regex pattern
    // 'r' in the string 's'. 'm' is flag for determining
    // matching behavior.
    regex_search(s, m, r);
  
    // for each loop
    for (auto x : m)
        cout << x << " ";
  
    return 0;
}

输出:

GeeksForGeeks

regex_replace()此函数用于用字符串替换与正则表达式匹配的模式。

// C++ program to demonstrate working of regex_replace()
#include 
#include 
#include 
#include 
using namespace std;
  
int main()
{ 
    string s = "I am looking for GeeksForGeek \n";
      
    // matches words beginning by "Geek"
    regex r("Geek[a-zA-z]+");
      
    // regex_replace() for replacing the match with 'geek' 
    cout << std::regex_replace(s, r, "geek");
      
    string result;
      
    // regex_replace( ) for replacing the match with 'geek'
    regex_replace(back_inserter(result), s.begin(), s.end(),
                  r,  "geek");
  
    cout << result;
  
    return 0;
}

输出:

I am looking for geek 
I am looking for geek

因此,正则表达式操作使用以下参数:-

  • 目标序列(主题)–要匹配的字符串。
  • 正则表达式(模式)–目标序列的正则表达式。
  • 匹配数组-有关匹配的信息存储在特殊的match_result数组中。
  • 替换字符串–这些字符串用于允许替换匹配项。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”