-1

Hey I am learning the regex and I am confused why this expression return 0? It should return 1 as the string "zy" matches in my expression..

#include <iostream>
#include <string>
#include <regex>
#include<bits/stdc++.h>
using namespace std;
 
int main() {

        string s2="ezyfo";
        bool result=regex_match(s2,regex("zy")) ;  
        cout<<result;                                    //output is 0 while "zy should match in the string s2
 
    return 0;
}

output is

0
Sachin
  • 1,206
  • 12
  • 13
  • I don't know this API, but if you use the patten `.*zy.*`, then [it works](https://rextester.com/MUN34394). – Tim Biegeleisen Jun 21 '20 at 05:06
  • `"ezyfo" ≠ "zy"` – Eljay Jun 21 '20 at 05:09
  • 5
    Just read the docs: https://en.cppreference.com/w/cpp/regex/regex_match. Specifically, "Note that `regex_match` will only successfully match a regular expression to an *entire* character sequence, whereas `std::regex_search` will successfully match subsequences." – eesiraed Jun 21 '20 at 05:09
  • why using only "zy" does not work as it also match in the s2 string.. – Sachin Jun 21 '20 at 05:10

2 Answers2

0

It should be like this. we need to format regex string correctly

#include <iostream>
#include <string>
#include <regex>
#include<bits/stdc++.h>
using namespace std;

int main() {

    string s2="ezyfo";
    regex match = regex("(.*)(zy)(.*)");
    bool result=regex_match(s2,match) ;
    cout<<result << endl;                             

 return 0;
}
  • what if I declared zy in seaparate string s2. How to should I provide arguement to regex? – Sachin Jun 21 '20 at 05:17
  • @Sachin Use [`std::regex_search`](https://en.cppreference.com/w/cpp/regex/regex_search) as explained in my comment. – eesiraed Jun 21 '20 at 05:28
  • You can use char array to solve your problem char regStr[] = "(.*)(zy)(.*)"; regex match = regex(regStr); – abhishek vishwakarma Jun 21 '20 at 05:29
  • @BessieTheCow thanks it worked for me... but still I am not clear why my solution not matched the s2 string – Sachin Jun 21 '20 at 05:38
  • Because `regex_match` has to match the **entire** target string, not just part of it. What you are looking for is `regex_search`, as already explained (three times now). – john Jun 21 '20 at 07:46
0

This works:

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string s2 = "ezyfo";
    std::regex match = std::regex("zy");
    bool result = std::regex_search(s2, match);
    std::cout << result << "\n";                             

 return 0;
}

Advantages compared to OP's implementation/other answers:

  • No .* required before and after the text snipped we are searching for. As @BessieTheCow pointed out std::regex_search searches for a substring whereas std::regex_match tries to match the entire string ("zy" ≠ ezyfo).

Bonus (not directly related to your question):

Martin Konrad
  • 1,075
  • 1
  • 10
  • 20