Regular Expression Basics in C++ - Linux Hint

文章推薦指數: 80 %
投票人數:10人

Commonly used functions for C++ regular expressions, are: regex_search(), regex_match() and regex_replace(). A regex is a pattern in double-quotes. However, ... Considerthefollowingsentenceinquotes: "Hereismyman." Thisstringmaybeinsidethecomputer,andtheusermaywanttoknowifithastheword“man”.Ifithasthewordman,hemaythenwanttochangetheword“man”to“woman”;sothatthestringshouldread: "Hereismywoman." Therearemanyotherdesireslikethesefromthecomputeruser;somearecomplex.RegularExpression,abbreviated,regex,isthesubjectofhandlingtheseissuesbythecomputer.C++comeswithalibrarycalledregex.So,aC++programtohandleregexshouldbeginwith: #include #include usingnamespacestd; ThisarticleexplainsRegularExpressionBasicsinC++. ArticleContent RegularExpressionFundamentals Pattern CharacterClasses MatchingWhitespaces ThePeriod(.)inthePattern MatchingRepetitions MatchingAlternation MatchingBeginningorEnd Grouping Theicaseandmultilineregex_constants MatchingtheWholeTarget Thematch_resultsObject PositionofMatch SearchandReplace Conclusion RegularExpressionFundamentals Regex Astringlike“Hereismyman.”aboveisthetargetsequenceortargetstringorsimply,target.“man”,whichwassearchedfor,istheregularexpression,orsimply,regex. Matching Matchingissaidtooccurwhenthewordorphrasethatisbeingsearchedforislocated.Aftermatching,areplacementcantakeplace.Forexample,after“man”islocatedabove,itcanbereplacedby“woman”. SimpleMatching Thefollowingprogramshowshowtheword“man”ismatched. #include #include usingnamespacestd; intmain() {   regexreg("man");   if(regex_search("Hereismyman.",reg))     cout<isanID",regex("ID[0-9]id")))  cout<"<"<"<"<5 seller->9 sel->9 ler->12 SearchandReplace Anewwordorphrasecanreplacethematch.Theregex_replace()functionisusedforthis.However,thistime,thestringwherethereplacementoccursisthestringobject,notthestringliteral.So,thestringlibraryhastobeincludedintheprogram.Illustration: #include #include #include usingnamespacestd; intmain() {   stringstr="Here,comesmyman.Theregoesyourman.";   stringnewStr=regex_replace(str,regex("man"),"woman");   cout<



請為這篇文章評分?