在 C 或 C++ 中使用 GNU 正则表达式函数
任何人都可以给我完整的示例程序如何在 gcc C 或 C++ 中使用 GNU 正则表达式函数 (http://docs.freebsd.org/info/regex/regex.info.GNU_Regex_Functions.html),与 re_pattern_buffer
、re_compile_fastmap
?
例如,翻译这个Python小程序:
import re
unlucky = re.compile('1\d*?3')
nums = ("13", "31", "777", "10003")
for n in nums:
if unlucky.search(n) is None:
print "lucky"
else:
print "unlucky"
谢谢!
Can anyone give me complete example program how to work with GNU regex functions in gcc C or C++ (http://docs.freebsd.org/info/regex/regex.info.GNU_Regex_Functions.html), withre_pattern_buffer
, re_compile_fastmap
?
For example, translate this small Python program:
import re
unlucky = re.compile('1\d*?3')
nums = ("13", "31", "777", "10003")
for n in nums:
if unlucky.search(n) is None:
print "lucky"
else:
print "unlucky"
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,在深入研究代码之前,我应该提到您可能想要使用更高级别的库。你确实说的是C++,所以这会让你进入 Boost.Regex 等。即使你想留在C,也有更好的选择。我发现 POSIX 函数 更干净,更不用说更便携了。
编辑:我添加了对必填字段和 regfree 的更多解释。我之前有过幸运/不幸的倒退,这解释了部分差异。另一部分是我认为此处可用的任何正则表达式语法都不支持惰性运算符(*?)。在这种情况下,有一个简单的修复方法,使用
"1[^3]*3"
。Okay, before delving into the code, I should mention that you may want to use a higher-level library. You did say C++, so that opens you up to Boost.Regex and the like. Even if you want to stay with C, there are better options. I find the POSIX functions somewhat cleaner, not to mention more portable.
EDIT: I added more explanation of the required fields, and the regfree. I had the lucky/unlucky backwards before, which explains part of the discrepancy. The other part is that I don't think any of the regex syntaxes available here support lazy operators (*?). In this case, there's a simple fix, using
"1[^3]*3"
.