使用正则表达式查找多个字符串的第一个实例
Find the first instance of multiple strings using regex
假设我有一个包含"ATGTTTGGATTAGGTAATGAAT"的字符串。
我想在字符串中搜索"TAG"、"TAA"或"TGA"的第一个实例。
为此,我想使用正则表达式。我认为std::regex_search
会起作用,但我不确定如何编写语法。
任何帮助将不胜感激。
编辑:我需要检索"TAG","TAA"或"TGA"的第一个实例的位置(以先到者为准)。
你可以试试这个:
#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;
}
文档在这里: http://en.cppreference.com/w/cpp/regex
你可以这样做:
#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;
}
我不知道
c++ 中的具体调用(也许这就是你要问的),但这是你的正则表达式:
/T(A[GA]|GA)/
也就是说,找到一个"T",后跟一个(一个"A"和一个["G"或"A"])或后跟"GA"。
对于这个特定问题(即,假设"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'
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 使用C 中字符串标头的getline()函数将第一个char存储在字符串对象中
- 在将字符串转换为整数后,是否有一种方法可以保持数字的第一个零
- 将第一个boost::regex匹配放入字符串中
- 有一个字符串如何从第一个' /r/n/r/n '得到它的内容,直到2行从字符串结束
- 删除二进制字符串中的第一个0