summaryrefslogtreecommitdiff
path: root/regex-search-example.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'regex-search-example.cpp')
-rw-r--r--regex-search-example.cpp34
1 files changed, 34 insertions, 0 deletions
diff --git a/regex-search-example.cpp b/regex-search-example.cpp
new file mode 100644
index 0000000..f77a566
--- /dev/null
+++ b/regex-search-example.cpp
@@ -0,0 +1,34 @@
+// regex_search example
+// NOTE:
+// std::regex_match matches the ENTIRE string
+// (as if with '^' and '$' anchors).
+// Use std::regex_search to match partial strings.
+#include <iostream>
+#include <string>
+#include <regex>
+
+using namespace std;
+
+int main ()
+{
+ string s ("synchronized chrysalis monochrome chromium chrX");
+ smatch m;
+ regex e ("\\b(chr)([^ ]*)");
+
+ cout << "words starting with 'chr':" << endl;
+
+ while (regex_search (s,m,e)) {
+ // The regex contained 2 groups, hence 'm' will contain
+ // Three items: [0] = Entire match
+ // [1] = The content of the first group ('chr')
+ // [2] = The content of the second group
+ cout << "word: '" << m[0] << "'"
+ << " suffix: '" << m[2] << "'" << endl;
+
+ // To find the next match, search in the suffix
+ // (the characters left after this match)
+ s = m.suffix().str();
+ }
+
+ return 0;
+}