开发者

Using Boost::Xpressive to match a single character

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 wo开发者_开发技巧uld my regex string need to be?

thanks


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜