boost 正規表示式解析配置檔案或命令列

liiinuuux發表於2016-09-26
從字串裡取欄位

點選(此處)摺疊或開啟

  1. int main()
  2. {
  3.     boost::regex re("<(.*)>[ ]+(\\S+)=(\\S+)[ ]+(\\S+)=(\\S+)[ ]+(\\S+)=(\\S+)[ ]+(\\S+)=(\\S+)[ ]+(\\S+)=(.*)");
  4.     boost::cmatch cm;
  5.     string s = "<test 1> ip=192.168.1.2 user=oracle every_sec=1 time=00:00:00 cmd=free -m ";

  6.     if(boost::regex_match(s.c_str(), cm, re))
  7.     {
  8.         cout << "matched string: '" << cm[0] << "'" << endl;
  9.         cout << cm.size()-1 << " part matched" << endl;
  10.         for(int i=1; i<cm.size(); i++) cout << "|"<<cm[i]<<"|" << endl;
  11.     }

  12.     return 0;
  13. }

輸出
[root@server2 test]# ./a
matched string: '<test 1> ip=192.168.1.2 user=oracle every_sec=1    time=00:00:00 cmd=free -m  '
11 part matched
|test 1|
|ip|
|192.168.1.2|
|user|
|oracle|
|every_sec|
|1|
|time|
|00:00:00|
|cmd|
|free -m  |

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26239116/viewspace-2125593/,如需轉載,請註明出處,否則將追究法律責任。

相關文章