C++ regular expression

Hi,

I am writing a program which takes as input, a sentence (string), and my program performs various checks on that sentence.
The following is a list of simplified version of the checks:
1. Count the number of words and output it.
2. Check if the first word is HAHA.
3. Check if any word in the sentence contains the letter D. If so, output that word.

I was thinking about using the C++ string operators such as find to do this. But, I simply can't think of a way to do it with those operations.

I'm used to solving such problems using Perl. So I was thinking about using a C++ regular expression library to do this. Would using regular expression library be an overkill? Also, which C++ regexp library do you recommend? (has to be one of the standard C++ library.) Preferably, I'd like to see a good guide about the library which you suggest.

Thank you
You can certainly use the regular expressions that are part of the standard C++ library:

http://www.cplusplus.com/reference/std/regex/
http://en.cppreference.com/w/cpp/regex

but it's not yet fully implemented by some compilers (most notably, GCC does not implement it, and does not throw errors or warnings if you try to use it)

The most portable choice today is boost.regex (which is almost exactly the same as the C++ regex)

http://www.boost.org/doc/libs/release/libs/regex/doc/html/index.html

However, the checks you listed don't require regular expressions: they are trivailly solvable with the more common string and stringbuffer operations, for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;
int main()
{
    string input = "HAHA, only kidDing";
    istringstream buf(input); // convert to buffer

    istream_iterator<string> beg(buf), end;
    vector<string> v(beg, end); // parse into words

    std::cout << "The number of words is " << v.size() << '\n';

    if(!v.empty() && v[0] == "HAHA")
        std::cout << "The first word is 'HAHA'\n";

    std::cout << "The following words contain the letter 'D': ";
    copy_if(v.begin(), v.end(), ostream_iterator<string>(cout),
            [](const string& s){ return s.find('D') != string::npos; });
    std::cout << '\n';
}
online demo: http://liveworkspace.org/code/06417fb98ccba1a8016c7b7299276c4e
Last edited on
Topic archived. No new replies allowed.