【问题标题】:Return all non-overlapping matches of pattern in string返回字符串中模式的所有非重叠匹配
【发布时间】:2010-02-12 21:39:26
【问题描述】:

在 Python 中,我可以使用 re.findall(pattern, string) 返回字符串中所有不重叠的模式匹配项。

例如,在以下 SVG 路径命令中:

import re
spam = "M317.0,169.7C311.1,170.5 285.7,146.8 300.7,178.57 L 321.4,175.01"
eggs = re.findall("([A-Za-z]|-?[0-9]+\.?[0-9]*(?:e-?[0-9]*)?)", spam)
print(eggs)
['M', '317.0', '169.7', 'C', '311.1', '170.5', '285.7', '146.8', '300.7', '178.5', 'L', '321.4', '175.0']

在 C 或 C++ 中,有一种轻量级、干净且有效的方法来进行这种类型的正则表达式模式匹配吗?请注意,我不是在寻找依赖于 Boost 的解决方案。理想情况下,我想尽量减少依赖关系并保持我的代码精简......

【问题讨论】:

  • 不幸的是,标准 C++ 语言不包含正则表达式函数。您必须使用std::string 构建一些东西,或者使用外部库
  • 你需要添加一些库,而 Boost 做了很多事情,本质上是终极的可移植性,那么为什么不使用它呢? (C++0x 添加了正则表达式,但这是一个在采用过程中添加到库中的速度很慢的特性。)
  • boost 是几乎所有 C++ 项目中都值得拥有的依赖项。

标签: c++ python regex pattern-matching


【解决方案1】:

SLRE - 超轻量级正则表达式库

SLRE 是一个 ANSI C 库,它实现了一小部分 Perl 正则表达式。它主要面向想要解析配置文件的开发人员,其中速度并不重要。它位于单个 .c 文件中,可根据自定义需求轻松修改。例如,如果要引入一个新的元字符“\i”,即“IP 地址”,那么很容易做到。 特点

* Crossplatform - pure ANSI C
* Very simple API
* Light: about 5kB of code when compiled
* Uses no dynamic memory allocation
* Thread safe

支持的 RE 语法

^ Match beginning of a buffer
$ Match end of a buffer
() Grouping and substring capturing
[...] Match any character from set
[^...] Match any character but ones from set
\s Match whitespace
\S Match non-whitespace
\d Match decimal digit
\r Match carriage return
\n Match newline
+ Match one or more times (greedy)
+? Match one or more times (non-greedy)
* Match zero or more times (greedy)
*? Match zero or more times (non-greedy)
? Match zero or once
\xDD Match byte with hex value 0xDD
@ 987654343@

/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * Sergey Lyubka wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return.
 * ----------------------------------------------------------------------------
 */

【讨论】:

    【解决方案2】:

    您需要一个 C++ 正则表达式库。它们有很多,但它们会产生依赖关系。 C++ 没有原生(或 STL)正则表达式支持。

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 2013-06-09
      • 2012-07-03
      相关资源
      最近更新 更多