How to match a set of characters (letter + any single character from set + letter) using RegEx in C++

2 Answers

0 votes
#include <iostream>
#include <regex>
#include <string>

// b[aeou]y: This pattern looks for strings that match the following:
// b: The letter "b".
// [aeou]: Any single character that is either "a", "e", "o", or "u".
// y: The letter "y".

void checkPattern(const std::string& pattern, const std::string& text) {
    std::regex re(pattern);
    bool match = std::regex_search(text, re);
    
    std::cout << (match ? "true" : "false") << std::endl;
}

int main() {
    const std::string pattern = "b[aeou]y";
    
    checkPattern(pattern, "A smart boy"); // b o y
    checkPattern(pattern, "I want to buy this laptop"); // b u y
    checkPattern(pattern, "baay");
    checkPattern(pattern, "baeouy");
    checkPattern(pattern, "baey");
    checkPattern(pattern, "This is beauty");
    checkPattern(pattern, "A programming book");
}


  
/*
run:
  
true
true
false
false
false
false
false
  
*/

 



answered Feb 25, 2025 by avibootz
edited Feb 25, 2025 by avibootz
0 votes
#include <iostream>
#include <regex>
#include <string>

// b[aeou]y: This pattern looks for strings that match the following:
// b: The letter "b".
// [aeou]: Any single character that is either "a", "e", "o", or "u".
// y: The letter "y".

bool checkPattern(const std::string& pattern, const std::string& text) {
    std::regex re(pattern);

    return std::regex_search(text, re);;
}

int main() {
    const std::string pattern = "b[aeou]y";
    
    std::cout << checkPattern(pattern, "A smart boy") << "\n"; // b o y
    std::cout << checkPattern(pattern, "I want to buy this laptop") << "\n"; // b u y
    std::cout << checkPattern(pattern, "baay") << "\n";
    std::cout << checkPattern(pattern, "baeouy") << "\n";
    std::cout << checkPattern(pattern, "baey") << "\n";
    std::cout << checkPattern(pattern, "This is beauty") << "\n";
    std::cout << checkPattern(pattern, "A programming book") << "\n";
}


  
/*
run:
  
1
1
0
0
0
0
0
  
*/

 



answered Feb 25, 2025 by avibootz
...