C++ regex character class not matching [duplicate]
Asked Answered
A

2

7

from what i researched, the expression "[:alpha:]" will be matched for any alphabetic character, but the expression only match for lowercase character and not uppercase character. I not sure what's wrong with it.

std::regex e ("[:alpha:]");
if(std::regex_match("A",e))
     std::cout<<"hi";
  else
     std::cout<<"no";
Austronesian answered 9/6, 2018 at 10:24 Comment(4)
"[:digit:]" doesnt work either when i want to match a digitAustronesian
Try with [[:alpha:]]Hastate
oh yours work! thxAustronesian
See cplusplus.com/reference/regex/ECMAScript : Please note that the brackets in the class names are additional to those opening and closing the class definition. For example: [[:alpha:]] is a character class that matches any alphabetic character. [abc[:digit:]] is a character class that matches a, b, c, or a digit.Exhort
H
6

Change this:

std::regex e ("[:alpha:]");

to:

std::regex e ("[[:alpha:]]");

As Adrian stated: Please note that the brackets in the class names are additional to those opening and closing the class definition. For example: [[:alpha:]] is a character class that matches any alphabetic character. Read more in the ref.

Honolulu answered 9/6, 2018 at 10:32 Comment(2)
And what if you want this class in a class? Say [a-zA-Z.-+/*], you write [[[:alpha]].-+/*] with 3 opening brackets?Anchovy
@Anchovy no: 2 brackets, not 3. And don't forget to escape the hyphen (-). So you write [[:alpha:].\-+/*].Rima
H
2

You have to use [[:alpha:]]

see online example

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main() {
    std::regex e ("[[:alpha:]]");
if(std::regex_match("A",e))
     std::cout<<"hi";
  else
     std::cout<<"no";
    return 0;
}
Hastate answered 9/6, 2018 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.