如何使用正则表达式提取文本中的所有名称

how to extract all the names in a text using regular expression

本文关键字:有名称 取文本 何使用 正则表达式 提取      更新时间:2023-10-16

英文名字就像哈利波特的格式,一个是名一个是姓。但是如何使用c++提取这种模式呢?

一个非常简单的正则表达式是/b([A-Z][a-z]+) ([A-Z][a-z]+)b/

编辑:这不能处理奇怪的大写和多余的撇号。

编辑:删除^$,放置单词边界

你可以这样开始。

#include<regex>
#include<iostream>
int main()
{
   // regular expression
   const std::regex pattern("([A-Z][a-z]+)s([A-Z][a-z]+)");
   // the source text
   std::string text = "string containing names ...";
   const std::sregex_token_iterator end;
   for (std::sregex_token_iterator i(text.cbegin(), text.cend(), pattern);
        i != end;
        ++i)
   {
      std::cout << *i << std::endl;
   }
   return 0;
}

学习正则表达式有帮助