stringから正規表現でマッチした箇所を抜き出す
最初にソース文字列を入れて、次に正規表現を何度も試せる非常にインタラクティブかつシンプルなコード例
regex_split.cpp
#include <iostream> #include <boost/regex.hpp> #include <string> using namespace std; using namespace boost; int main(int argc, char* argv[]){ cout << "--input source string" << endl; string str; getline(cin, str); while(true){ string regex_str; cout << "--input regex" << endl; getline(cin, regex_str); regex delimiter(regex_str); vector<string> results; string s = str; // regex_splitするとソース文字列が破壊されるので regex_split(back_inserter(results), s, delimiter); cout << str << endl; for(int i = 0; i < results.size(); i++){ cout << '"' << results[i] << '"' << endl; } } return 0; }
コンパイルする
g++ -O regex_split.cpp -o regex_split -I/opt/local/include/boost /opt/local/lib/libboost_regex-mt.a
実行
./regex_split
--input source string 1,2,3.5 a. jkalsdf, / hogeasd, s --input regex ([a-zA-Z]+) 1,2,3.5 a. jkalsdf, / hogeasd, s "a" "jkalsdf" "hogeasd" "s" --input regex ([a-zA-Z]{1,5}) 1,2,3.5 a. jkalsdf, / hogeasd, s "a" "jkals" "df" "hogea" "sd" "s" --input regex ([a-zA-Z]{3,10}) 1,2,3.5 a. jkalsdf, / hogeasd, s "jkalsdf" "hogeasd"