匹配一个单词的模式并提取整个单词

Match a word for pattern and extracting the whole word

本文关键字:单词 模式 提取 一个      更新时间:2023-10-16

我正在尝试编写一个函数,该函数将单个单词的一部分与输入的文本相匹配,并在该单词中存在该模式的情况下打印整个单词。我正在使用c++。请帮忙。下面是我尝试使用字符串函数编写的一个函数,但有了这个函数,我只能知道一个单词是否存在于句子中。但我需要提取一个单词,它的部分与输入的文本相匹配。我希望我的问题很清楚。

#include <cctype>
#include <iostream>
#include <string>
bool contains_word(const std::string& sentence, const std::string& word)
{
    size_t pos = 0;
    // Find the start of 'word' in 'sentence'.
    while ((pos = sentence.substr(pos).find(word)) != std::string::npos) {
            if (!(isalpha(sentence[pos - 1])) || !(isalpha(sentence[pos + word.size() +1])))
                    return true;
    }
    return false;
}
std::string get_word(const std::string& sentence, const std::string& substr)
{
  std::string::size_type it = sentence.find(substr);
  if(it == std::string::npos)
    return "";
  std::string::size_type it2 = it;
  for(; it >= 1 && !std::isspace(sentence[it - 1]); --it);
  for(; it2 <= sentence.size() - 1 && !std::isspace(sentence[it2 + 1]); ++it2);
  return sentence.substr(it, (it2 + 1) - it);
}
int main()
{
  std::string str("kchmviewer gnome-terminal");
  std::cout << get_word(str, "viewer") << std::endl;
  std::cout << get_word(str, "terminal") <<std::endl;
  return 0;
}

输出为:

kchmviewer 
gnome-terminal