boost:regex

regex
1.介绍
header:"boost/regex.hpp"
正则表达式是一个basic_regex的对象。

template <class charT,class Allocator,class traits >
  bool regex_match(
    const charT* str,
    match_results<const charT*,Allocator>& m,
    const basic_regex<charT,traits >& e,
    match_flag_type flags = match_default);

regex_match决定一个正则表达式(参数e)是否匹配整个字符串str。主要用于确认文本。

template <class charT,class Allocator, class traits>
  bool regex_search(
    const charT* str,
    match_results<const charT*,Allocator>& m,
    const basic_regex<charT,traits >& e,
    match_flag_type flags = match_default);

regex_search与regex_match相似,但它不要求整个字符串成功匹配。用来发现与正则表达式e匹配的子串。

template <class traits,class charT>
  basic_string<charT> regex_replace(
    const basic_string<charT>& s,
    const basic_regex<charT,traits >& e,
    const basic_string<charT>& fmt,
    match_flag_type flags = match_default);

regex_replace扫描字符串查找所有与正则表达式匹配的子串,并用参数fmt替代。



regex需要单独编译。

2.regex使用
 首先声明一个basic_regex的变量。用来存储正则表达式。
 例如:boost:regex reg("(A.*)");
       通配符.表示匹配任意字符。*表示它前面的表达式匹配零次或多次。+表示前面的表达式至少出现一次。
   [abc]表示匹配a,b,c中的任意一个。也可写为[a-c]。匹配字母可写为[a-zA-Z]或\w。
   匹配2个数字或字符串“N/A” (\\d{2}|N/A),|用来分离可选项。
   \s 表示空格。
      \n(n为数字) 表示引用前面的第n个表达式。("\\d{3}([a-zA-Z]+).(\\d{2}|N/A)\\s\\1") \1引用[a-zA-Z]+,两者必须匹配相同的字符串。
3.确认输入
  正则表达式最常见的用法是确认输入数据的格式。
 手动编写这样的代码是乏味的易错的,而且需要适应需求的变化。

4.查找
 match_results记录匹配后的位置,为下一次匹配作记录。
5.循环与贪婪
 避免贪婪匹配,在循环后加?
                   "(.*)(\\d{2})"
  "Note that I'm 31 years old, not 32."
       "(.*?)(\\d{2})"

循环匹配
 1)*,+,{},?(单独使用,表示匹配零次或一次)。
 boost::regex reg1("\\d{5}");匹配5次
 boost::regex reg2("\\d{2,4}");匹配2,3,4次
 boost::regex reg3("\\d{2,}");匹配2次或2次以上
 2)^用于匹配不是指定的字符。
 ("[^13579]");匹配不是1,3,5,7,9的字符。

异常处理
 表达式不正确,执行时会抛出异常。


posted on 2008-06-30 23:12 guaiguai 阅读(1174) 评论(0)  编辑 收藏 引用 所属分类: boost


只有注册用户登录后才能发表评论。
相关文章:
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜