0

I have a string that can be "/" "+" "." or a descriptive name

I'm trying to figure out how to use regex to check if the string matches any of the 3 special characters above (/ + or .)

After doing a bit of reading i decided boost::xpressive was the way to go but i still cannot figure it out.

is Boost:xpressive suitable for this task and what would my regex string need to be?

thanks

hipyhop
  • 179
  • 4
  • 12

2 Answers2

2

Why not just use std::string::find_first_of() to do your own solution? Sounds like a lot of machinery for a fairly simple task.

Edit

Try this out if you're still stuck.

#include <iostream>
#include <boost/xpressive/xpressive.hpp>

using namespace std;
using namespace boost::xpressive;

int main()
{
   sregex re = sregex::compile("[+./]|[:word:]+");

   sregex op = as_xpr('+') | '.' | '/';
   sregex rex = op | (+alpha);

   if (regex_match(string("word"), re))
      cout << "word" << endl;
   if (regex_match(string("word2"), re))
      cout << "word2" << endl;
   if (regex_match(string("+"), re))
      cout << "+" << endl;
   return 0;
}

There are two ways to do the same thing shown. The variable named re is intialized with a perl-like regular expression string. rex uses Xpressive native elements.

gregg
  • 1,027
  • 5
  • 6
  • I'm trying to learn about regex and i couldn't figure the solution to the question above. I think it was the escaped characters next to each other was confusing me. – hipyhop Dec 10 '10 at 15:25
  • 1
    @TomFLuff: Well then, that's different. Regular expressions are very powerful tools, so keep on digging into them. Just keep in mind not to overly complicate a solution to use something cool (I constantly have to remind myself of this). – gregg Dec 10 '10 at 16:08
1

I would say that Boost.Xpressive may be overkill for the task, but it's your call.

Regular expression are life savers when you want to validate a particularly formatted string. Here, there is no format involved, only a set of possible values. My advice : if your problem can be solved by simple, successive string equality comparisons, than you probably don't need anything like regular expressions.

icecrime
  • 74,451
  • 13
  • 99
  • 111