0

I'm using C++ on XCode. I'd like to match non-alphabet characters using regex_match but seem to be having difficulty:

#include <iostream>
#include <regex>

using namespace std;

int main(int argc, const char * argv[])
{
    cout << "BY-WORD: " << regex_match("BY-WORD", regex("[^a-zA-Z]")) << endl;
    cout << "BYEWORD: " << regex_match("BYEWORD", regex("[^a-zA-Z]")) << endl;

    return 0;
}

which returns:

BY-WORD: 0
BYEWORD: 0

I want "BY-WORD" to be matched (because of the hyphen), but regex_match returns a 0 for both tests.

I confoosed.

0

2 Answers 2

2

regex_match tries to match the whole input string against the regular expression you provide. Since your expression would only match a single character, it will always come back false on those inputs.

You probably want regex_search instead.

Sign up to request clarification or add additional context in comments.

Comments

2

regex_match() returns whether the target sequence matches the regular expression rgx. If you want to search the non-alphabet characters from the target sequence, you need regex_search():

#include <regex>
#include <iostream>
int main()
{
    std::regex rx("[^a-zA-Z]");
    std::smatch res;
    std::string str("BY-WORD");
    while (std::regex_search (str,res,rx)) {
        std::cout <<res[0] << std::endl;
        str = res.suffix().str();
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.