2017-03-21 2 views
1

J'ai un regex python:C++ 11 regex confusion

\A\s*      # optional whitespace at the start, then 
(?P<sign>[-+]?)   # an optional sign, then 
(?=\d|\.\d)    # lookahead for digit or .digit 
(?P<num>\d*)    # numerator (possibly empty) 
(?:      # followed by 
    (?:/(?P<denom>\d+))? # an optional denominator 
|       # or 
    (?:\.(?P<decimal>\d*))? # an optional fractional part 
    (?:E(?P<exp>[-+]?\d+))? # and optional exponent 
) 
\s*\Z      # and optional whitespace to finish 

En d'autres termes, obtenir des groupes nommés pour:

  • signé/non signé | rationnel/décimal/entier | numéro | avec/sans exposant

Mais je suis confondu avec le format regex C++ 11? Comme je l'ai lu il y a peu de formats supportés, mais je reçois une exception d'analyseur regex avec celui-ci. Plus, j'ai lu que le groupe nommé n'est pas pris en charge avec C++ 11 regex. Comment avoir une expression rationnelle compatible C++ 11 qui fournit un schéma équivalent?

Merci beaucoup pour votre aide.

Répondre

1

Vous ne pouvez pas conserver les groupes de capture nommés, mais vous pouvez utiliser une chaîne multiligne littérale pour définir le motif d'une manière prolixe:

std::string pat = "^\\s*"  // optional whitespace at the start, then 
     "([-+]?)"    // an optional sign, then 
     "(?=\\.?\\d)"   // lookahead for digit or .digit 
     "(\\d*)"    // numerator (possibly empty) 
     "(?:"     // followed by 
      "(?:/(\\d+))?"  // an optional denominator 
     "|"     // or 
      "(?:\\.(\\d*))?" // an optional fractional part 
      "(?:E([-+]?\\d+))?" // and optional exponent 
     ")" 
     "\\s*$";    // and optional whitespace to finish 
std::regex e(pat); 
std::string s(" -23/34 "); 
std::smatch a; 
if (std::regex_search(s, a, e)) 
    std::cout << a[0] << endl; 

Voir la C++ demo

+0

Rock You. Pour information, quel est le style regex que vous utilisez ici? posix? –

+1

Non, c'est ECMAScript 5. POSIX ne supporte pas les lookaheads, et il y en a un ici, '(? = \\.? \\ d)'. –