【问题标题】:How to extract the unmatched portion of a string using a regex如何使用正则表达式提取字符串的不匹配部分
【发布时间】:2017-02-12 19:59:28
【问题描述】:

当输入无效时,我正在尝试向用户显示一些消息。

我写了这个正则表达式来验证这个模式:(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;
    }
}

【问题讨论】:

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

标签: c++ regex visual-c++


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 2017-11-19
    • 2014-12-30
    • 2021-12-30
    • 2022-10-01
    相关资源
    最近更新 更多