Monday, May 24, 2010

Using regular expressions in C++?

If you have a string of text





(for example, "1234 quick 1234 brown 1234 fox")





and you wanted to use a regular expression to identify any words in that string of text, what is the c++ code that would do it?





Note: A word is defined as any sequence of letters that is not interrupted by a space.





I could really use an example of code.





What #include statements would I need? Is there a way to do it without including regex? Where do I get regex (if I try to include it now, my compiler gives me an error, so I assume I need to get it from somewhere)?





Please note, I don't need a tutorial on regular expressions. I understand regular expressions well enough as it is, I just need to know how to use them in C++.

Using regular expressions in C++?
well... one way would be to search through the string until you found a space, or CR/LF.





Im not sure what you want to do when you find them but something like this will count them:





char mystring[] = "1234 quick 1234 brown 1234 fox";


int count, words = 0, spaces = 0, crlf = 0;


BOOL wordsstart = 1;





for (count = 0; count %26lt; sizeof(mystring); count++)


{


if (mystring[count] == 0x20) //space


{


spaces++;


wordstart = 1;


}


else if (mystring[count] == 0x0a || mystring[count] == 0x0d) //carriage return or line feed


{


crlf++;


wordstart = 1;


}


else if (wordstart %26amp;%26amp; ((mystring[count] %26gt;= 'a' %26amp;%26amp; mystring[count] %26lt;= 'z') || (mystring[count] %26gt;= 'A' %26amp;%26amp; mystring[count] %26lt;= 'Z')))


{


words++;


wordstart = 0;


}


}





its just off the top of my head, but it should work
Reply:google up pcre





http://www.pcre.org/!


No comments:

Post a Comment