Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is a potential match for regex

Tags:

c++

regex

Basically, I want to be able to have a regular expression, such as #[0-9]+ and be able to check if a string could match it. For example, if I am getting user input and they enter "#" this string is not a match to the regex, but could be if the user entered some numbers as well.

I know C++ has the matches() functions, but is there anything out there like what I am looking for? Or some way to do it?

like image 475
Pottsiex5 Avatar asked Nov 03 '15 12:11

Pottsiex5


1 Answers

You can use Boost.Regex, which already implements Partial Matches.

When used it indicates that partial as well as full matches should be found. A partial match is one that matched one or more characters at the end of the text input, but did not match all of the regular expression (although it may have done so had more input been available).

Code

#include <iostream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;


int main  () {
    string subject = "#";
    string pattern = "#[0-9]+";


    const regex e(pattern);
    if (regex_match(subject, e, match_partial)) {
        cout << subject << " \tMATCHES\t " << pattern << endl;
    } else {
        cout << subject << " \tDOESN'T MATCH\t " << pattern << endl;
    }


    return 0;
}

rextester demo

like image 198
Mariano Avatar answered Oct 26 '22 09:10

Mariano