Algoteka
Log in to submit your own samples!

Match with a Regex Pattern

Problem by oml1111
# Tech tags Title Creator Created date
1 0
2022-12-19 19:00
View all samples for this language (1 verified and 0 unverified)

STL solution | C++ |

By oml1111 |
0 likes

Does the matching using the std::regex_match

Code

#include<regex>
#include<string>

int main() {
    std::string text = "the integer a equals 353, whereas b = 12";
    
    std::regex pattern("the integer a equals (\\d+), whereas b = (\\d+)");
    std::smatch match;
    
    if(std::regex_match(text, match, pattern)) {
        std::string a = match[1];  // acquires value "353"
        std::string b = match[2];  // acquires value "12"
    }

    return 0;
}

Further reading

<regex> - cplusplus.com
ECMAScript syntax - cplusplus.com

References

classes
std::regex en.cppreference.com cplusplus.com
std::smatch en.cppreference.com cplusplus.com
std::string en.cppreference.com cplusplus.com
functions
std::regex_match en.cppreference.com cplusplus.com

Problem Description

Construct a regex pattern with some groups. Use said pattern to check if some string matches the pattern and then fetch the parts of the string that match the groups in that pattern.

View sample discussion (0 comments)
View problem discussion (0 comments)