boost regex expression

Boost.Regex provides three different functions to search for regular expressions

1. regex_match

#include <boost/regex.hpp>
#include <string>
#include <iostream>

int main() {
  std::string s = "Boost Libraries";
  boost::regex expr("\\w+\\s\\w+");
  std::cout << std::boolalpha << boost::regex_match(s, expr) << std::endl;
  return 0;
}

boost::regex_match() compares a string with a regular expression. It will return true only if the expression matches the complete string.

2. regex_search

#include <boost/regex.hpp>
#include <string>
#include <iostream>

int main() {
  std::string s = "Boost Libraries";
  boost::regex expr("(\\w+)\\s(\\w+)");
  boost::smatch what;
  if (boost::regex_search(s, what, expr)) {
    std::cout << what[0] << std::endl;
    std::cout << what[1] << "_" << what[2] << std::endl;
  }
  return 0;
}

3. regex_replace

#include <boost/regex.hpp>
#include <string>
#include <iostream>

int main() {
  std::string s = " Boost Libraries";
  boost::regex expr("\\s");
  std::string fmt("_");
  std::cout << boost::regex_replace(s, expr, fmt) << std::endl;
  return 0;
}

 

4. boost xpressive

Like boost regex, boost xpressive provides functions to search strings using regular expressions. However, boost xpressive makes it possible to write down regular expressions as C++ code rather than strings. That makes it possible to check at compile time whether a regular expression is valid or not.

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

using namespace boost::xpressive;

int main() {
  std::string s = "Boost Libraries";
  sregex expr = sregex::compile("\\w+\\s\\w+");
  std::cout << std::boolalpha << regex_match(s, expr) << std::endl;
  return 0;
}

boost::xpressive::regex_match() compares strings, boost::xpressive::regex_search() searches in strings, and boost::xpressive::regex_replace() replaces characters in strings. The type of regular expression in boost xpressive depends on the type of string being searched. Because s is based on std::string, the type of the regular expression must be boost::xpressive::sregex.

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

using namespace boost::xpressive;

int main() {
   const char* c = "Boost Libraries";
   cregex expr = cregex::compile("\\w+\\s\\w+");
   std::cout << std::boolalpha << regex_match(c, expr) << std::endl;
   return 0;
}

For strings of type const char*, use the class boost::xpressive::cregex.

 

转载于:https://www.cnblogs.com/sssblog/p/10981214.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值