在Unix上使用C ++的正则表达式

时间:2010-02-08 20:46:06

标签: c++ regex unix

我对Regex本身很熟悉,但每当我试图找到任何用于在Unix计算机上使用正则表达式的示例或文档时,我只会获得有关如何编写正则表达式或如何使用适用于Windows的.NET特定库的教程。我一直在寻找一段时间,我在Unix机器上找不到关于C ++正则表达式的任何好的教程。

我正在尝试做什么:

使用正则表达式解析一个字符串,然后将其分解,然后读取不同的子组。要进行PHP类比,比如preg_match,返回所有$匹配。

8 个答案:

答案 0 :(得分:13)

考虑使用Boost.Regex

一个例子(来自网站):

bool validate_card_format(const std::string& s)
{
   static const boost::regex e("(\\d{4}[- ]){3}\\d{4}");
   return regex_match(s, e);
}

另一个例子:

// match any format with the regular expression:
const boost::regex e("\\A(\\d{3,4})[- ]?(\\d{4})[- ]?(\\d{4})[- ]?(\\d{4})\\z");
const std::string machine_format("\\1\\2\\3\\4");
const std::string human_format("\\1-\\2-\\3-\\4");

std::string machine_readable_card_number(const std::string s)
{
   return regex_replace(s, e, machine_format, boost::match_default | boost::format_sed);
}

std::string human_readable_card_number(const std::string s)
{
   return regex_replace(s, e, human_format, boost::match_default | boost::format_sed);
}

答案 1 :(得分:9)

查看TR1正则表达式的文档或(几乎等效地)提升正则表达式。两者在各种Unix系统上都能很好地工作。 TR1正则表达式类已经被接受到C ++ 0x中,所以尽管它们还不是标准的一部分,但它们很快就会合适。

编辑:要将字符串分成子组,可以使用sregex_token_iterator。您可以指定要作为标记匹配的内容,或者要作为分隔符匹配的内容。以下是两者的快速演示:

#include <iterator>
#include <regex>
#include <string>
#include <iostream>

int main() { 

    std::string line;

    std::cout << "Please enter some words: " << std::flush;
    std::getline(std::cin, line);

    std::tr1::regex r("[ .,:;\\t\\n]+");
    std::tr1::regex w("[A-Za-z]+");

    std::cout << "Matching words:\n";
    std::copy(std::tr1::sregex_token_iterator(line.begin(), line.end(), w),
        std::tr1::sregex_token_iterator(), 
        std::ostream_iterator<std::string>(std::cout, "\n"));

    std::cout << "\nMatching separators:\n";
    std::copy(std::tr1::sregex_token_iterator(line.begin(), line.end(), r, -1), 
        std::tr1::sregex_token_iterator(), 
        std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}

如果你给它这样的输入:“这是一些999文本”,结果是这样的:

Matching words:
This
is
some
text

Matching separators:
This
is
some
999
text

答案 2 :(得分:0)

您正在寻找regcomp, regexec and regfree

需要注意的一点是,Posix正则表达式实际上实现了两种不同的语言:常规(默认)和扩展(在调用regcomp时包含标志REG_EXTENDED)。如果您来自PHP世界,扩展语言更接近您习惯的。

答案 3 :(得分:0)

对于perl兼容的正则表达式(pcre / preg),我建议boost.regex

答案 4 :(得分:0)

我最好的选择是boost::regex

答案 5 :(得分:0)

试试pcre。并pcrepp

答案 6 :(得分:0)

请随意查看我写的这个小颜色grep工具。

github

它使用R Samuel Klatchko所指的regcomp,regexec和regfree。

答案 7 :(得分:0)

我使用“GNU正则表达式”:http://www.gnu.org/s/libc/manual/html_node/Regular-Expressions.html

运行良好但无法找到UTF-8正则表达式的明确解决方案。

此致