..

정규표현식

정규 표현식으로 C++ 클래스 이름 표현하기

유효한 C++ 클래스 이름을 정규 표현식으로 나타내자면 아래처럼 쓸 수 있다.

^[A-Za-z_][A-za-z0-9]*

c++ sample code

    std::regex pattern( "^[A-Za-z_][A-Za-z0-9]*" );
    std::cout << "Is Match : " << std::regex_match( "12",  pattern ); //Is Match : 0
    std::cout << "Is Match : " << std::regex_match( "_12", pattern ); //Is Match : 1
    std::cout << "Is Match : " << std::regex_match( "*A",  pattern ); //Is Match : 0
    std::cout << "Is Match : " << std::regex_match( "AB&", pattern ); //Is Match : 0

0부터 99까지의 수로 시작하고 끝나는 문자열

아래 4개의 정규 표현식은 모두 동일하게 0부터 99까지의 수로 시작해서 끝나는 문자열을 나타낸다.

//method 1
^[0-9]{1,2}

//method 2
^\d{1,2}$

//method 3
^\d\d{0,1}$

//method 4
^\d\d?$

특정 문자열 찾기

|은 or를 의미. 따라서 mail 이나 letter를 포함하는 문자열이 매칭됨.

//qt
QRegularExpression re("letter|mail");
qDebug() << re.match("email").hasMatch();       // true
qDebug() << re.match("mailbox").hasMatch();     // true
qDebug() << re.match("mail").hasMatch();        // true
qDebug() << re.match("letters").hasMatch();     // true

//c++11
std::regex pattern( "letter|mail" );
std::cout << std::regex_search( "email", pattern ) << std::endl;    // 1
std::cout << std::regex_search( "mailbox", pattern ) << std::endl;  // 1
std::cout << std::regex_search( "mail", pattern ) << std::endl;     // 1
std::cout << std::regex_search( "letters", pattern ) << std::endl;  // 1

Note

std::regex_match는 전체 입력이 모두 매칭될 때만 true를 반환한다. std::regex_search는 입력의 일부분만 매칭되도 true를 반환한다. 따라서, 위 코드에서 std::regex_match를 사용했다면 “mail”과 비교한 경우만 true고, 나머지는 false다. StackOverFlow

()은 capture하려고 하는 부분을 명시. 소괄호로 묶음으로써 더 복잡한 정규 표현식을 사용할 수 있다. \b는 단어의 시작과 끝을 매칭하는 word boundary를 뜻함.

//qt
QRegularExpression re("\\b(letter|mail)\\b");
qDebug() << re.match("email").hasMatch();       // false
qDebug() << re.match("mailbox").hasMatch();     // false
qDebug() << re.match("mail").hasMatch();        // true
qDebug() << re.match("letters").hasMatch();     // false
qDebug() << re.match("letter").hasMatch();      // true

//c++11
std::regex pattern( "\\b(letter|mail)\\b" );
std::cout << std::regex_search( "email", pattern ) << std::endl;    // 0
std::cout << std::regex_search( "mailbox", pattern ) << std::endl;  // 0
std::cout << std::regex_search( "mail", pattern ) << std::endl;     // 1
std::cout << std::regex_search( "letters", pattern ) << std::endl;  // 0
std::cout << std::regex_search( "letter", pattern ) << std::endl;   // 1

참고 1) QT QRegExp
참고 2) regex101.com/