【问题标题】:C++ Regex to match words without punctuationC ++正则表达式匹配没有标点符号的单词
【发布时间】:2011-01-28 06:22:05
【问题描述】:

我搜索了,找不到任何东西。为了不再浪费我的时间在答案对其他人来说是显而易见的机会上,我在这里问。到目前为止,唯一有用的网站是这个:http://softwareramblings.com/2008/07/regular-expressions-in-c.html,但样本太简单了。我正在使用 Visual Studio 2010。

#include <regex>

[...]

string seq = "Some words. And... some punctuation.";
regex rgx("\w");

smatch result;
regex_search(seq, result, rgx);

for(size_t i=0; i<result.size(); ++i){
    cout << result[i] << endl;
}

预期的输出是:

一些


一些
标点符号

谢谢。

【问题讨论】:

  • 我不怪你没有做对。我在这方面看到的文档很难。

标签: c++ regex tr1


【解决方案1】:

这里有一些东西。

首先,您的正则表达式字符串需要将\ 转义。毕竟它仍然是一个 C++ 字符串。

regex rgx("\\w");

另外,正则表达式\w只匹配一个“单词字符”。如果要匹配整个单词,则需要使用:

regex rgx("\\w+");

最后,为了遍历所有可能的匹配项,您需要使用迭代器。这是一个完整的工作示例:

#include <regex>
#include <string>
#include <iostream>
using namespace std;

int main()
{
    string seq = "Some words. And... some punctuation.";
    regex rgx("\\w+");

    for( sregex_iterator it(seq.begin(), seq.end(), rgx), it_end; it != it_end; ++it )
        cout << (*it)[0] << "\n";
}

【讨论】:

  • 我完全忘记了仍然需要转义字符串。发布的另一个答案有效,我需要的唯一补充是它忽略任何只有数字的单词。
  • @Chris:@Eugene 打败了我,因为我花了额外的时间来解释更多的东西并给你一个完整的工作示例 :)
  • @Chris:更棘手。我认为,您需要使用某种形式的前瞻。看这里:regular-expressions.info/refadv.html
  • 在第二阶段丢弃“仅数字”结果可能更容易。使用正则表达式当然是微不足道的,但还有很多其他方法(例如find_first_not_of
  • @MSalters:是的,我可能也会这样做。
【解决方案2】:

试试这个:

string seq = "Some words. And... some punctuation.";
regex rgx("(\\w+)");

regex_iterator<string::iterator> it(seq.begin(), seq.end(), rgx);
regex_iterator<string::iterator> end;

for (; it != end; ++it)
{
    cout << it->str() << endl;
}

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2015-01-01
    相关资源
    最近更新 更多