2017-02-12 53 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 
相关问题