2015-10-06 69 views
0

我真的不知道我做錯了什麼。我已經檢查了正則表達式中http://regexpal.com/和它工作得很好使用正則表達式驗證輸入

這裏是我的代碼:

std::string text = "1.98"; 
std::regex regex_number("((\b[0-9]+)?\.)?[0-9]+\b"); 
bool isValid = std::regex_match(text, regex_number); 

應該爲整數,有效和雙打 例:

  • 1.2
  • 1.99
  • 0.6

不適用於

  • AA
  • DD
  • 1.2H
  • 1,6

我得到的一切非有效文本。

+1

如果你想檢查是否字符串具有有效的int或加倍你可以使用boost中的lexical_cast。 boost :: lexical_cast (text),boost :: lexical_cast (text)should help。如果文本不是有效數字,Lexical_cast將引發異常。 – cppcoder

回答

2

你忘了逃避你反斜線字符串文字中:

std::regex regex_number("((\\b[0-9]+)?\\.)?[0-9]+\\b"); 
+0

100%正確答案 – guilhermecgs

1

您還堅持那首詞分隔符的位置錯誤。它應該是可選的部分外:

"\\b(([0-9]+)?\\.)?[0-9]+\\b" 

(很抱歉的附加應答;我還沒有代表添加註釋)