2017-02-12 92 views
0

我想在輸入無效時向用戶顯示一些消息。如何使用正則表達式提取字符串的不匹配部分

我寫此正則表達式,以validade這種模式:(10個字符名稱)(0-9之間號)

例如布魯諾3

^([\w]{1,10})(\s[\d]{1})$ 

當用戶輸入任何無效的字符串,是否有可能知道什麼組是無效的,並打印消息? 類似的東西:

if (regex_match(user_input, e)) 
{ 
    cout << "input ok" << endl; 
} 
else 
{ 
    if (group1 is invalid) 
    { 
     cout << "The name must have length less than 10 characters" << endl; 
    } 

    if (group2 is invalid) 
    { 
     cout << "The command must be between 0 - 9" << endl; 
    } 
} 
+1

'[\ d] {1}'可以是'\ d' – 4castle

+0

您提出了哪些代碼?它有什麼問題? –

+0

@WiktorStribiżew我編輯了問題 – Bruno

回答

1

當我看到你想匹配1 to 10 character話單space,然後單digit但在2

這裏是你想要的東西:

^([a-zA-Z]{1,10})(\d)$

備註

\w相當於[a-zA-Z0-9_]
所以,如果你只需要10個字符,你應該使用[a-zA-Z]\w


C++代碼

std::string string("abcdABCDxy 9"); 

std::basic_regex<char> regex("^([a-zA-Z]{1,10})(\\d)$"); 
std::match_results<std::string::const_iterator> m_result; 

std::regex_match(string, m_result, regex); 
std::cout << m_result[ 1 ] << '\n'; // group 1 
std::cout << m_result[ 2 ] << '\n'; // group 2 

輸出

1abcdABCDxy 
9