C++ 使用正则表达式查找多个字符串的第一个实例

C++ 使用正则表达式查找多个字符串的第一个实例,c++,regex,C++,Regex,假设我有一个包含“atgtttggattagtaatgaat”的字符串 我想在字符串中搜索“TAG”、“TAA”或“TGA”的第一个实例 为此,我想使用正则表达式。我认为std::regex_search可以工作,但我不确定如何编写语法 任何帮助都将不胜感激 编辑:我需要检索“TAG”、“TAA”或“TGA”(以先到者为准)的第一个实例的位置。您可以这样做: #include <iostream> using namespace std; int main() { strin

假设我有一个包含“atgtttggattagtaatgaat”的字符串

我想在字符串中搜索“TAG”、“TAA”或“TGA”的第一个实例

为此,我想使用正则表达式。我认为
std::regex_search
可以工作,但我不确定如何编写语法

任何帮助都将不胜感激

编辑:我需要检索“TAG”、“TAA”或“TGA”(以先到者为准)的第一个实例的位置。

您可以这样做:

#include <iostream>
using namespace std;
int main()
{
    string str="ATGTTTGGATTAGGTAATGAAT";
    string regstr="TAG";
    const char *show;

    show=strstr(str.c_str(), regstr.c_str());//return the pointer of the first place reg 'TAG',else return NULL。
    cout<<show<<endl;
    return 0;
}
#包括
使用名称空间std;
int main()
{
字符串str=“atgtttggattagtaatgaat”;
字符串regstr=“TAG”;
常量字符*显示;
show=strstrstr(str.c_str(),regstr.c_str());//返回第一位reg'TAG'的指针,否则返回NULL

CUT< P>我不知道C++中的特定调用(也许这就是你要问的),但这是你的正则表达式:

/T(A[GA]|GA)/
也就是说,找到一个“T”后跟(a)和[“G”或“a”])或后跟“GA”。

您可以尝试以下方法:

#include <iostream>
#include <regex>

int main() {
    std::string s("ATGTTTGGATTAGGTAATGAAT");
    std::regex r("TAG|TAA|TGA");
    std::sregex_iterator first(s.begin(), s.end(), r);
    std::cout << "position: " << first->position() << std::endl; // position: 10
    return 0;
}
#包括
#包括
int main(){
std::字符串s(“atgtttggattagtaatgaat”);
标准::正则表达式r(“TAG | TAA | TGA”);
std::sregex_迭代器优先(s.begin(),s.end(),r);
std::cout对于这个特定问题(即,假设“TAG”、“TAA”和“TGA”是要搜索的字符串,而不仅仅是更一般问题的代表),简单搜索更容易:

find 'T'
  if the next character is 'A' and the character after that is 'A' or 'G', matched;
  else if the next character is 'G' and the character after that is 'A' matched;
  else go back and try the next 'T'

当一个简单的“find”可以工作时,为什么要用正则表达式来做这件事呢?或者仅仅是“strstr”?find将找到一个子字符串,但不是一组子字符串的第一个出现我想我只需要使用类似“TAG | TAA | TGA”的东西.这绝对是一个开始。但我需要找出具体的调用和获得位置的方法。将我的正则表达式插入上给出的示例中(注意:不包括外部斜线)。这实际上是我的工作基础,但我没有得到我想要的结果。我真的只需要位置(索引)三个字符串中第一个出现的。我会继续尝试。