2015-05-06 23 views
2

有了這個輸入:如何創建一個匹配直到但不包括空格的字符串的正則表達式?

"hello the3re world" 

我試圖創建一個正則表達式將匹配一個只包含字母字符,而不是數字的話。

我用標準std :: regex_constants :: match_continuous使用std :: regex_search。 有了這個正則表達式[[:alpha:]]+第一次調用regex_search會讓我回到「你好」。如果我繼續前進「你好」和任何空白區域,然後再次嘗試「the3re world」,我會回到:「the」。

但是,現在我真正想要的是失敗,因爲「3」在單詞中不應該有效。

+1

那麼[az] +? – Creris

+0

難道你不能使用拉丁字母的自定義字符類:'\ b [a-zA-Z] + \ b'?你在使用Visual Studio嗎?請發佈您的代碼。 –

+3

另外..你需要使用單詞邊界....與你的正則表達式它應該是'\ b [[:alpha:]] + \ b' –

回答

2

(添加一個答案我的意見),你應該使用單詞邊界\b用於這一目的..

\b[[:alpha:]]+\b //or "\\b[[:alpha:]]+\\b" as per the syntax.. 
+0

是的,它適用於\\ b's。測試。 :)來自我的提醒,提醒您關於ECMAScript語法http://www.cplusplus.com/reference/regex/ECMAScript/。 –

+0

感謝您驗證它.. :) –

2

您可以使用下面的代碼:

string line1 = "hello the3re world"; 
string regexStr1 = "\\b[a-zA-Z]+\\b"; 
regex rg1(regexStr1); 
smatch sm1; 
while (regex_search(line1, sm1, rg1)) { 
     std::cout << sm1[0] << std::endl; 
     line1 = sm1.suffix().str(); 
} 

輸出:

enter image description here

相關問題