Home > Back-end >  How to extract the character between spaces using regex?
How to extract the character between spaces using regex?

Time:09-26

I want to extract the character between spaces using regex?

For example, if I have the string "CHARACTER[ " ]", I want to extract the char " " ".

If I have the string "CHARACTER[ ! ]", I want to extract the char " ! ".

If I have the string "CHARACTER[ G ]", I want to extract the char " G ".

CodePudding user response:

Sometimes the type of character helps to narrow it down. A character class like [a-z] is a good start and put that in a \s sandwich.

CodePudding user response:

I wrote this given the examples you've shown so it wont allow for a lot of deviation.

I haven't tested this extensively but something like this should at least get you going.

#include <iostream>
#include <string>
#inclue <regex>


int main( ) {
    const std::regex regex{ R"(^\w \[\s?(.*?)\s?\]$)" };

    // If you want to limit it to only matching a pattern with a
    // single character between the brackets use this instead.
    // const std::regex regex{ R"(^\w \[\s?(.)\s?\]$)" };

    const std::string test{ R"(CHARACTER[!])" };

    std::smatch match{ };
    if ( std::regex_match( test, match, regex ) && match.size( ) > 1 ) {
        std::cout << "Found: " << match[ 1 ].str( ) << '\n';
    }
} 
  •  Tags:  
  • c
  • Related