Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling a 'wildcard' character in C++

Tags:

c++

I need a function to identify a pattern string within another string while taking into consideration a wildcard character _

For instance, if the given pattern is f__h, then it should match up to the string catfish.

So essentially, the underscore needs to be able to represent any alphabetical character, but I can't think of a way to go about this. Anyone got some ideas on how to do this?

Thanks.

like image 820
user2773084 Avatar asked Jan 25 '26 16:01

user2773084


2 Answers

With new standard C++11 you can use regex. Otherwise use boost regex.

like image 169
Jepessen Avatar answered Jan 28 '26 08:01

Jepessen


What's wrong with:

std::search(
    text.begin(), text.end(),
    pattern.begin(), pattern.end(),
    []( char fromText, char fromPattern ) {
        return fromPattern == '_' || fromPattern == fromText;
    } )

If the function returns text.end(), there was no match. Otherwise, it returns an iterator to the first character of the match.

like image 25
James Kanze Avatar answered Jan 28 '26 07:01

James Kanze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!