`
cwqcwk1
  • 浏览: 89291 次
文章分类
社区版块
存档分类
最新评论

C++ regex 正则表达式的使用

 
阅读更多

在c++中,有三种正则可以选择使用,C ++regex,C regex,boost regex ,如果在windows下开发c++,默认不支持后面两种正则,如果想快速应用,显然C++ regex比较方便使用。文章将讨论C++ regex 正则表达式的使用。

C++ regex函数有3个:regex_match、regex_search 、regex_replace

regex_match

regex_match是正则表达式匹配的函数,下面以例子说明。如果想系统的了解,参考regex_match

// regex_match example
#include <iostream>
#include <string>
#include <regex>

int main ()
{

  if (std::regex_match ("subject", std::regex("(sub)(.*)") ))
    std::cout << "string literal matched\n";

  std::string s ("subject");
  std::regex e ("(sub)(.*)");
  if (std::regex_match (s,e))
    std::cout << "string object matched\n";

  if ( std::regex_match ( s.begin(), s.end(), e ) )
    std::cout << "range matched\n";

  std::cmatch cm;    // same as std::match_results<const char*> cm;
  std::regex_match ("subject",cm,e);
  std::cout << "string literal with " << cm.size() << " matches\n";

  std::smatch sm;    // same as std::match_results<string::const_iterator> sm;
  std::regex_match (s,sm,e);
  std::cout << "string object with " << sm.size() << " matches\n";

  std::regex_match ( s.cbegin(), s.cend(), sm, e);
  std::cout << "range with " << sm.size() << " matches\n";

  // using explicit flags:
  std::regex_match ( "subject", cm, e, std::regex_constants::match_default );

  std::cout << "the matches were: ";
  for (unsigned i=0; i<sm.size(); ++i) {
    std::cout << "[" << sm[i] << "] ";
  }

  std::cout << std::endl;

  return 0;
}
输出如下:

string literal matched
string object matched
range matched
string literal with 3 matches
string object with 3 matches
range with 3 matches
the matches were: [subject] [sub] [ject]

regex_search

regex_match是另外一个正则表达式匹配的函数,下面是regex_search的例子。regex_search和regex_match的主要区别是:regex_match是全词匹配,而regex_search是搜索其中匹配的字符串。如果想系统了解,请参考regex_search

// regex_search example
#include <iostream>
#include <regex>
#include <string>

int main(){
  std::string s ("this subject has a submarine as a subsequence");
  std::smatch m;
  std::regex e ("\\b(sub)([^ ]*)");   // matches words beginning by "sub"

  std::cout << "Target sequence: " << s << std::endl;
  std::cout << "Regular expression: /\\b(sub)([^ ]*)/" << std::endl;
  std::cout << "The following matches and submatches were found:" << std::endl;

  while (std::regex_search (s,m,e)) {
    for (auto x=m.begin();x!=m.end();x++) 
      std::cout << x->str() << " ";
    std::cout << "--> ([^ ]*) match " << m.format("$2") <<std::endl;
    s = m.suffix().str();
  }
}

输出如下:

Target sequence: this subject has a submarine as a subsequence
Regular expression: /\b(sub)([^ ]*)/
The following matches and submatches were found:
subject sub ject --> ([^ ]*) match ject
submarine sub marine --> ([^ ]*) match marine
subsequence sub sequence --> ([^ ]*) match sequence

/********  无情的分割线 ********* /    
  作者:没有开花的树    
  博客:blog.csdn.net/mycwq    
/ *******   无情的copy  *********/
regex_replace

regex_replace是替换正则表达式匹配内容的函数,下面是regex_replace的例子。如果想系统了解,请参考regex_replace

#include <regex> 
#include <iostream> 
 
int main() { 
    char buf[20]; 
    const char *first = "axayaz"; 
    const char *last = first + strlen(first); 
    std::regex rx("a"); 
    std::string fmt("A"); 
    std::regex_constants::match_flag_type fonly = 
        std::regex_constants::format_first_only; 
 
    *std::regex_replace(&buf[0], first, last, rx, fmt) = '\0'; 
    std::cout << &buf[0] << std::endl; 
 
    *std::regex_replace(&buf[0], first, last, rx, fmt, fonly) = '\0'; 
    std::cout << &buf[0] << std::endl; 
 
    std::string str("adaeaf"); 
    std::cout << std::regex_replace(str, rx, fmt) << std::endl; 
 
    std::cout << std::regex_replace(str, rx, fmt, fonly) << std::endl; 
 
    return 0; 
} 
输出如下:
AxAyAz
Axayaz
AdAeAf
Adaeaf

C++ regex正则表达式的规则和其他编程语言差不多,如下:

特殊字符(用于匹配很难形容的字符):

characters description matches
. not newline any character exceptline terminators(LF, CR, LS, PS).
\t tab (HT) a horizontal tab character (same as\u0009).
\n newline (LF) a newline (line feed) character (same as\u000A).
\v vertical tab (VT) a vertical tab character (same as\u000B).
\f form feed (FF) a form feed character (same as\u000C).
\r carriage return (CR) a carriage return character (same as\u000D).
\cletter control code a control code character whosecode unit valueis the same as the remainder of dividing thecode unit valueofletterby 32.
For example:\cais the same as\u0001,\cbthe same as\u0002, and so on...
\xhh ASCII character a character whosecode unit valuehas an hex value equivalent to the two hex digitshh.
For example:\x4cis the same asL, or\x23the same as#.
\uhhhh unicode character a character whosecode unit valuehas an hex value equivalent to the four hex digitshhhh.
\0 null a null character (same as\u0000).
\int backreference the result of the submatch whose opening parenthesis is theint-th (intshall begin by a digit other than0). Seegroupsbelow for more info.
\d digit a decimal digit character
\D not digit any character that is not a decimal digit character
\s whitespace a whitespace character
\S not whitespace any character that is not a whitespace character
\w word an alphanumeric or underscore character
\W not word any character that is not an alphanumeric or underscore character
\character character the charactercharacteras it is, without interpreting its special meaning within a regex expression.
Anycharactercan be escaped except those which form any of the special character sequences above.
Needed for:^ $ \ . * + ? ( ) [ ] { } |
[class] character class the target character is part of the class
[^class] negated character class the target character is not part of the class
注意了,在C++反斜杠字符(\)会被转义
std::regex e1 ("\\d");  //  \d -> 匹配数字字符
std::regex e2 ("\\\\"); //  \\ -> 匹配反斜杠字符

数量

characters times effects
* 0 or more The preceding atom is matched 0 or more times.
+ 1 or more The preceding atom is matched 1 or more times.
? 0 or 1 The preceding atom is optional (matched either 0 times or once).
{int} int The preceding atom is matched exactlyinttimes.
{int,} intor more The preceding atom is matchedintor more times.
{min,max} betweenminandmax The preceding atom is matched at leastmintimes, but not more thanmax.

注意了,模式 "(a+).*" 匹配 "aardvark" 将匹配到 aa,模式 "(a+?).*" 匹配 "aardvark" 将匹配到 a

(用以匹配连续的多个字符):

characters description effects
(subpattern) Group Creates a backreference.
(?:subpattern) Passive group Does not create a backreference.
注意了,第一种将创建一个反向引用,用于提取匹配到的内容,第二种则没有,相对来说性能方面也没这部分的开销

characters description condition for match
^ Beginning of line Either it is the beginning of the target sequence, or follows aline terminator.
$ End of line Either it is the end of the target sequence, or precedes aline terminator.
| Separator Separates two alternative patterns or subpatterns..

单个字符

[abc] 匹配 a, b 或 c.
[^xyz] 匹配任何非 x, y, z的字符

范围
[a-z] 匹配任何小写字母 (a, b, c, ..., z).
[abc1-5] 匹配 a, b , c, 或 1 到 5 的数字.

c++ regex还有一种类POSIX的写法

class description equivalent (withregex_traits, default locale)
[:alnum:] alpha-numerical character isalnum
[:alpha:] alphabetic character isalpha
[:blank:] blank character isblank
[:cntrl:] control character iscntrl
[:digit:] decimal digit character isdigit
[:graph:] character with graphical representation isgraph
[:lower:] lowercase letter islower
[:print:] printable character isprint
[:punct:] punctuation mark character ispunct
[:space:] whitespace character isspace
[:upper:] uppercase letter isupper
[:xdigit:] hexadecimal digit character isxdigit
[:d:] decimal digit character isdigit
[:w:] word character isalnum
[:s:] whitespace character isspace

参考:

http://blog.csdn.net/mycwq/article/details/18838151

http://www.cplusplus.com/reference/regex/


分享到:
评论

相关推荐

    C++正则表达式-regex类(不依赖其他库)

    C++正则表达式是C++11标准引入的一个强大工具,它允许程序员使用正则表达式进行文本模式匹配和搜索。在这个特定的案例中,我们关注的是`regex`类,它是C++ `&lt;regex&gt;`库的一部分,用于实现正则表达式操作。这个压缩包...

    c++写的正则表达式验证工具

    Boost库的正则表达式组件,即`boost::regex`,是C++实现正则表达式的常用选择之一,它提供了一套完整的API接口,使得在C++中编写正则表达式相关的代码变得相对简单。 在Visual Studio 2008环境下,开发者可以将...

    C++ BOOST 正则表达式使用教程

    C++ BOOST 正则表达式使用教程 正则表达式是一种用来描述一定数量文本的模式,用于匹配和处理大量规则的文本格式。 Regex 代表 Regular Express。C++ 中使用 Boost 库的 regex 类来实现正则表达式。 正则表达式的...

    C++ 正则表达式 使用手册 源代码

    C++中的正则表达式是通过标准库 `&lt;regex&gt;` 提供的,这使得在C++程序中处理文本和模式匹配变得十分便捷。本手册聚焦于如何有效地利用C++的正则表达式功能,以实现高效且灵活的字符串操作。下面我们将深入探讨C++正则...

    C++ 使用正则表达式demo

    C++11及以后的标准中引入了`&lt;regex&gt;`库,提供了一套完整的正则表达式API,包括`std::regex_match`,`std::regex_search`和`std::regex_replace`等函数。但在VS2008中,由于该版本遵循的是C++03标准,因此不包含这些...

    C++Regex正则表达式

    总之,C++的Regex正则表达式为开发者提供了强大的文本处理能力,无论是简单的文本匹配,还是复杂的模式查找和替换,都能得心应手。学习和掌握正则表达式是提升C++编程技能的重要环节,对于处理大量文本数据尤其有用...

    Linux C Regex正则表达式 库

    综上所述,"Linux C Regex正则表达式库"提供了在C语言中使用正则表达式的关键功能,经过修改后适用于Android环境,使得开发者可以在移动设备上进行复杂文本处理和模式匹配。通过理解和掌握这些核心概念,开发者能够...

    regex正则表达式插件

    在安装这个“regex正则表达式插件”后,用户通常可以通过Eclipse的“帮助”菜单找到相关的配置和使用指南。安装过程可能需要访问Eclipse Marketplace或者通过本地安装包进行。一旦安装完成,插件通常会在Eclipse的...

    C++深入浅出之正则表达式

    - 在C++中使用正则表达式时,由于编译器的处理,可能需要对特殊字符进行额外的转义,比如`C:\\temp`在正则表达式中需要写成`C:\\\\temp`。 正则表达式在C++中的应用广泛,包括文件处理、数据验证、文本分析等场景...

    VC、VC++,MFC 正则表达式类库

    在标准C++库中,虽然没有内置的正则表达式支持,但通过包含如 Boost 或 TR1(Technical Report 1)扩展,或者在较新的C++11及更高版本中使用&lt;regex&gt;库,开发者可以实现正则表达式功能。然而,对于MFC开发者来说,...

    正则表达式(regex)C语言源码,超强查找/替换算法

    正则表达式(Regular Expression,简称regex)是编程领域中一种强大的文本处理工具,它用于在字符串中查找、替换或匹配特定模式。在C语言中,实现正则表达式功能通常需要借助第三方库,比如本案例中提到的Henry ...

    C++代码实例:正则表达式

    ### C++代码实例:正则表达式 #### 知识点概述 本示例通过一个C++程序展示了如何实现简单的正则表达式匹配。在实际应用中,正则表达式是一种强大的文本处理工具,用于模式匹配、搜索和替换等操作。在本案例中,...

    C/C++ Regex/Regular Expression(C/C++正则表达式库实现)

    在C/C++编程环境中,正则表达式(Regex或Regular Expression)是一种强大的文本处理工具,用于模式匹配、字符串查找、替换等操作。由于C++标准库并没有内置完整的正则表达式支持,直到C++11标准引入了`&lt;regex&gt;`库,...

    C++ 正则表达式匹配工具源码

    正则表达式引擎通常被封装在标准库中,C++11及其后续版本引入了`&lt;regex&gt;`库,使得开发者可以直接在C++中使用正则表达式功能。 在"C++ 正则表达式匹配工具源码"中,我们可以期待看到一系列类和函数,它们是基于`...

    c++11中regex正则表达式示例简述

    C++11中regex正则表达式示例简述 ...C++11中的regex正则表达式库提供了强大的字符串匹配和处理功能,通过使用std::regex类、std::match_results类和三个匹配函数,我们可以轻松地进行字符串匹配和处理操作。

    c++正则表达式用法及示例

    C++中的正则表达式是通过标准库 `&lt;regex&gt;` 提供的功能,允许程序员进行复杂的文本匹配和处理。正则表达式是一种模式匹配工具,能够快速有效地查找、替换或分割字符串。在C++中,理解并熟练运用正则表达式可以极大地...

    c++用的正则表达式包

    本节将详细讲解如何在C++中使用Boost库的正则表达式功能。 首先,`c++boost.gif`可能是一个图标或示例图片,用于展示Boost库与C++的结合。`regex.htm`可能是一个关于Boost正则表达式的HTML文档,包含教程或API参考...

    c、c++最常用的正则表达式集合

    由于C++11标准已经内置了正则表达式库,我们可以直接使用标准库中的&lt;regex&gt;来处理上述正则表达式。不过,需要注意的是,C语言标准库本身并不支持正则表达式,使用正则表达式时通常需要借助外部库如PCRE或者POSIX ...

    SQL 语法分析,正则表达式解析C#文件;正则表达式实现的语法分析引擎

    在C#编程中,可以使用`System.Text.RegularExpressions`命名空间中的`Regex`类来处理正则表达式。`Regex`类提供了多种方法,如`Match`、`Matches`和`Replace`,分别用于执行单次匹配、多次匹配和替换操作。通过编写...

    Boost.Regex.C++正则表达式快速入门[整理].pdf

    Boost.Regex.C++正则表达式快速入门[整理].pdf

Global site tag (gtag.js) - Google Analytics