2010-09-03 55 views
0

包括

#include <algorithm> 
#include<boost/algorithm/string.hpp> 
#include<boost/regex.hpp> 
    using namespace std; 
    using namespace boost; 

    string _getBasehtttp(string url) 
    { 

     regex exrp("^(?:http://)?([^\\/]+)(.*)$"); 

     match_results<string::const_iterator> what; 

     if(regex_search(url, what, exrp)) 

     { 

      string base(what[1].first, what[1].second); 

      return base; 
     } 
     return ""; 
} 
int main() { 

    cout << _getBasehtttp("httpasd://www.google.co.in"); 
} 

如果我输入http://www.google.co.in我正在返回www.google.com但如果我输入httpasd://www.google.co.in我得到httpasd ..there不应该有任何的比赛呐Ÿ我得到了比赛???最新错误与我的C + + boost正则表达式函数?

回答

0

^(?:http://)?([^\\/]+)(.*)$

的?在(?:http://)?末意味着位是可选的
([^\\/]+)捕获并匹配任何不是一个\或/
(.*)抓住一切直到行结束

也许你更多的东西一样 后^(?:https?://)([^\\/]+)(.*)$

不妨考虑完整的URL语法沿着

file://          /C:/temp/app/example.html 
file://  C        : /temp/app/example.html 
file://  C        : \temp\app\example.html 
http://[email protected]:8080/test/url.htm?view=smart 
[method][    server     ][ path ][optional] 
     [user][   domain    ][port] 

那么你的小时线eading更多像

([a-zA-Z][a-zA-Z0-9\\+\\-\\.]*://)?(([^@/\\\\][email protected])?([a-zA-Z0-9_'!~\\-,;&=\\.\\$\\*\\(\\)\\+]+)(:\\d*)?)?([/\\\\][^?]*)?(\\?.*)? 
2

http://不匹配,但它是可选的,所以这没问题; “一个或多个不是斜杠的字符”匹配httpasd:,当然.*匹配后面的所有内容,从斜线(包括)开始。这与任何常见的正则表达式实现都是一样的,没有任何C++特有的!

+0

正则表达式u能告诉我,我怎么能说得对正则表达式 – raj 2010-09-03 20:56:01

+0

@raj,这完全取决于_what_你想匹配,并且你想什么** **不匹配。我很高兴@Greg能够推测这一点(我从你的接受中推断出来),因为我的思维阅读能力有限;-)。 – 2010-09-03 21:28:10