Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用正则表达式提取字符串中不匹配的部分_C++_Regex_Visual C++ - Fatal编程技术网

C++ 如何使用正则表达式提取字符串中不匹配的部分

C++ 如何使用正则表达式提取字符串中不匹配的部分,c++,regex,visual-c++,C++,Regex,Visual C++,我试图在输入无效时向用户显示一些消息 我写了这个正则表达式,以验证这个模式:(10个字符的名称)(0-9之间的数字) e、 g.布鲁诺3 ^([\w]{1,10})(\s[\d]{1})$ 当用户输入任何无效字符串时,是否可以知道哪个组无效并打印消息? 诸如此类: if (regex_match(user_input, e)) { cout << "input ok" << endl; } else { if (group1 is invalid)

我试图在输入无效时向用户显示一些消息

我写了这个正则表达式,以验证这个模式:(10个字符的名称)(0-9之间的数字)

e、 g.布鲁诺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;
    }
}
if(正则表达式匹配(用户输入,e))
{

cout正如我看到的,您希望匹配
1到10个字符
,然后是单个
空格
,然后是单个
数字
,但在2组中

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   
以下是您想要的:

注意

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   
\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   

[\d]{1}
可以是
\d
你想出了什么代码以及它有什么问题?@WiktorStribiżew我编辑了这个问题你输入字符串的长度是多少因为没有内置功能知道正则表达式的哪个部分失败了,你只能用2个
正则表达式搜索来解决它,一个带有
^\w{1,10}
和第二个带有
\s\d$
regexps的。