Regex是“的缩写” 正则表达式 “,在编程语言和许多不同的库中经常以这种方式使用。它在C++11以后的编译器中受支持。 正则表达式中使用的函数模板 regex_match() -如果正则表达式与给定字符串匹配,则此函数返回true,否则返回false。
null
CPP
// C++ program to demonstrate working of regex_match() #include <iostream> #include <regex> using namespace std; int main() { string a = "GeeksForGeeks" ; // Here b is an object of regex (regular expression) regex b( "(Geek)(.*)" ); // Geek 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' " ; // 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" ; 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() –此函数用于搜索与正则表达式匹配的模式
CPP
// C++ program to demonstrate working of regex_search() #include <iostream> #include <regex> #include<string.h> 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() 此函数用于用字符串替换与正则表达式匹配的模式。
CPP
// C++ program to demonstrate working of regex_replace() #include <iostream> #include <string> #include <regex> #include <iterator> using namespace std; int main() { string s = "I am looking for GeeksForGeek " ; // 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
因此,正则表达式操作使用以下参数:-
- 目标序列(主题)–要匹配的字符串。
- 正则表达式(模式)–目标序列的正则表达式。
- 匹配数组–有关匹配的信息存储在一个特殊的匹配结果数组中。
- 替换字符串–这些字符串用于允许替换匹配项。
本文由 阿比纳夫·蒂瓦里 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END