Reputation: 1844
Suppose I have a string containing "ATGTTTGGATTAGGTAATGAAT".
I'd like to search the string for the first instance of either "TAG", "TAA", or "TGA".
To do this, I'd like to use regular expressions. I think std::regex_search
will work, but I'm unsure how to write the syntax.
Any help would be greatly appreciated.
EDIT: I need to retrieve the position of the first instance of "TAG", "TAA", or "TGA" (whichever comes first).
Upvotes: 2
Views: 921
Reputation: 76345
For this specific problem (that is, assuming that "TAG", "TAA", and "TGA" are the strings to be searched for, and not just representatives of a more general problem), a simple search is easier:
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'
Upvotes: 0
Reputation: 4316
You can try this:
#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;
}
doc is here: http://en.cppreference.com/w/cpp/regex
Upvotes: 3
Reputation: 1936
I don't know the specific call in c++ (maybe that's what you are asking about), but this is your regex:
/T(A[GA]|GA)/
That is, find a "T" followed by either (an "A" and a ["G" or "A"]) or followed by "GA".
Upvotes: 0
Reputation: 350
You can do like this:
#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;
}
Upvotes: 0