tags:

views:

124

answers:

3

I have mutliple regex expressions, each mapped to a different object. After passing in a string, I want to loop through each regex expression until one evaluates to true, then I would like to return the mapped object.

What is the best way to implement this in C++? Is there a boost object available for this?

A: 

Use the Boost precog class.It was developed by pkdick. For example:

int main() {
  boost::precog p;
  p.do();
}

Alternatively, use a for-next loop to iterate over a vector of regexes.

anon
But what if I didn't want to do that? :O
Ron Warholic
Your choice is predestined.
anon
I had to google boost precog before I figure this out.
caspin
+1  A: 

Assuming you have a vector (or other container) of these objects that contain the regex's, you could do this with a std::find_if call. Tricky part is writing the correct predicate functor.

Dan
If writing the predicate is tricky, why even suggest this solution?
anon
wow neil rather snarky today! are you drunk?
caspin
Nope. Can I expect you or Dan to provide the tricky predicate?
anon
@Neil, it isn't that tricky, I just didn't feel like doing the grunt work. The answer suggests an approach, isn't that good enough? I'll provide details after I see your implementation of boost::precog.
Dan
A: 

The simplest approach is probably best.

vector<pair<regex,Object>> regexes;

Object* find_it( string looking_for )
{
    auto found = find_if( regexes, [&]( const pair<regex,Object>& thing )
     {
      return get<0>(thing).match(looking_for);
     }

    if( found != regexes.end() ) return & get<1>(*found);

    return nullptr;
}

But, the simple approach is never a fun answer. If you use a Trie you can essentially have fast look up for regexes of the style <prefix>.*. With a little imagination you might be able to muster good look up time for slightly more expressive "regexes". I, however, doubt you could transform a trie to efficiently handle general regexes. But it could be fun to ... trie :).

caspin