2

I have a string say:

std::string s1 = "@Hello$World@";

I want to match it with another string but only certain characters:

std::string s2 = "_Hello_World_";

The strings must have same length and exactly match ignoring the _ characters which can be anything. In other words, I want to match the sequence of "Hello" and "World" at same indexes.

I could use a loop here ignoring those indexes but I want to know if I can do this with regex expressions?

1
  • In regex, a dot matches any character (except newlines), so your regex would have to look like .Hello.World.. Commented Oct 17, 2015 at 10:29

2 Answers 2

3

The '.' (dot) operator inside a regex pattern will act as a substitute for any char. Below you have 3 strings with different separators that are matched by the pat variable...

#include <iostream>
#include <regex>

using namespace std;

int main()
{
    regex pat(".Hello.World.");
    // regex pat(.Hello.World., regex_constants::icase); // for case insensitivity

    string str1 = "_Hello_World_";
    string str2 = "@Hello@World@";
    string str3 = "aHellobWorldc";

    bool match1 = regex_match(str1, pat);
    bool match2 = regex_match(str2, pat);
    bool match3 = regex_match(str3, pat);

    cout << (match1 ? "Matched" : "Not matched") << endl;
    cout << (match2 ? "Matched" : "Not matched") << endl;
    cout << (match3 ? "Matched" : "Not matched") << endl;


    //system("pause");
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Yes, you can just use std::regex_match like so:

std::string string("@Hello$World@");
std::regex regex("^.Hello.World.$");
std::cout << std::boolalpha << std::regex_match(string, regex);

Live demo

The . (dots) in the regex mean "any character", ^ means "starting of the string" and $ means ending of the string.

6 Comments

Is it also possible to match any lower case character instead of just any character?
@user963241 Yes, with classes. Please, if you have any other question, open a new question instead of asking them here. The reason for this is that Stack Overflow is optimized for single straight forward questions + related answers; questions and answers in comments may not even be indexed well by search engines.
Thanks. I want know just one thing related to the answer: if it is really necessary to use ^ and $ in regex. I think it works without them as well.
@user963241 Depends on whether you want to match .Hello.World. anywhere in a string or match only if the whole string matches .Hello.World..
But it still doesn't work for anywhere
|

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.