[英]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 .) 我试图弄清楚如何使用正则表达式来检查字符串是否与上面的3个特殊字符(/ +或。)匹配。
After doing a bit of reading i decided boost::xpressive was the way to go but i still cannot figure it out. 经过一番阅读后,我决定使用boost :: xpressive是可行的方法,但我仍然无法弄清楚。
is Boost:xpressive suitable for this task and what would my regex string need to be? Boost:xpressive是否适合此任务,我的正则表达式字符串需要是什么?
thanks 谢谢
Why not just use std::string::find_first_of()
to do your own solution? 为什么不只使用
std::string::find_first_of()
做自己的解决方案? 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. 名为
re
的变量使用类似perl的正则表达式字符串进行初始化。 rex
uses Xpressive native elements. rex
使用Xpressive本机元素。
I would say that Boost.Xpressive may be overkill for the task, but it's your call. 我想说,Boost.Xpressive可能对这项任务有些过分,但这是您的要求。
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.
我的建议:如果您的问题可以通过简单的连续字符串相等比较来解决,那么您可能不需要正则表达式之类的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.