c++regexvisual-c++regex-groupnmea

Validating an NMEA sentence using C++


I need help with creating regular expressions for NMEA sentence. The reason for this because I want to validate the data whether it is a correct form of NMEA sentence. Using C++. Below is some example of NMEA sentence in the form of GLL. If it's possible I would also like to get a sample of c++ that will validate the code.

$GPGLL,5425.32,N,106.92,W,82808*64

$GPGLL,5425.33,N,106.91,W,82826*6a

$GPGLL,5425.32,N,106.9,W,82901*5e

$GPGLL,5425.32,N,106.89,W,82917*61

I have also included the expression I have tried that I found it online. But when I run it, it says unknown escape sequence.

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

int main()
{
    // Target sequence
    string s = "$GPGLL, 54 30.49, N, 1 06.74, W, 16 39 58 *5E";

    // An object of regex for pattern to be searched
    regex r("[A-Z] \w+,\d,\d,(?:\d{1}|),[A-B],[^,]+,0\*([A-Za-z0-9]{2})");

    // flag type for determining the matching behavior
    // here it is for matches on 'string' objects
    smatch m;

    // regex_search() for searching the regex pattern
    // 'r' in the string 's'. 'm' is flag for determining
    // matching behavior.
    regex_search(s, m, r);

    // for each loop
    for (auto x : m)
        cout << "The nmea sentence is correct ";

    return 0;
}

Solution

  • The C++ compiler interprets \d and friends as a character escape code.

    Either double the backslashes:

    regex r("[A-Z] \\w+,\\d,\\d,(?:\\d{1}|),[A-B],[^,]+,0\\*([A-Za-z0-9]{2})");
    

    or use a raw literal:

    regex r(R"re([A-Z] \w+,\d,\d,(?:\d{1}|),[A-B],[^,]+,0\*([A-Za-z0-9]{2}))re");