【问题标题】:looping over string to see where the string failed循环遍历字符串以查看字符串失败的位置
【发布时间】:2012-03-12 09:35:16
【问题描述】:

我希望能够遍历正在针对正则表达式进行测试的字符串,如果它未能输出与字符串的其余部分一起失败的位置。

boost::regex const string_matcher("[0-9]{5}");
if (boost::regex_match(12A45,string_matcher))
{
    DCS_LOG_DEBUG("Correct\n");                     
}
else
{
    DCS_LOG_DEBUG("Incorrect\n");
}

所以这个输出是

"A45"

【问题讨论】:

  • 一般情况下无法回答。如果您有一个正则表达式(a.b)|(ac[de]),匹配aee 在位置3(不是b)或位置2(不是c)失败。当一种可能性不起作用时,正则表达式引擎会回溯,这是一个二元决策。它不会跟踪“它走了多远”。因此,我的示例中的数字“3”没有被存储。

标签: c++ regex string boost


【解决方案1】:

你会使用类似的东西:

(^[0-9]{5}$)|^(?:[0-9]{0,5})(.*)$

有两个捕获和一个非捕获组((?:...) 中的那个)

第一个用于“正确”数据。该字符串由 5 位数字组成。否则会跳过 0-5 位数字,并将第一个“错误”字符放入第二次捕获 (.?)。请注意,即使字符串为空,此捕获也会成功。

小样本:

std::regex const string_matcher("(^[0-9]{5}$)|^(?:[0-9]{0,5})(.*)$");
std::match_results<std::string::const_iterator> match;
std::string str("123456");

std::cout << "Success: " << std::boolalpha << std::regex_match(str, match, string_matcher) << std::endl;
std::cout << "Num of sub-matches: " << match.size() << std::endl;
std::cout << "Success capture: " << std::boolalpha << match[1].matched << " at " << match.position(1) << ": '" << match[1].str() << "'" << std::endl;
std::cout << "First failed character: " << std::boolalpha << match[2].matched << " at " << match.position(2) << ": '" << match[2].str() << "'" << std::endl;

(遗憾的是我无法在ideone上编译它,因为它不支持正则表达式,在VC++上测试过)

测试它:

(empty string)
1
AA
1AA
12345
123456
12345AA

【讨论】:

  • 好吧,正则表达式也是如此...boost::regex const string_matcher("(?&lt;Success&gt;^[0-9]{5}$)|^(?:[0-9]{0,5})(?&lt;Failure&gt;.)$"); 或者是某种strings 的成功和失败?
  • @ShamariCampbell 添加了一个新段落
  • 我试过'12A45',它说失败发生在-1,这不正确吗?
  • 所以如果我有^(?:[0-9]{0,5})(.*)$,它会将错误和字符串的其余部分放在match[2]等中?
  • 啊,好吧,我知道这一切是如何结合在一起的 :)
【解决方案2】:

你可以做的是:

循环遍历字符串的字符,当结果不正确时循环,使用 indexof(chr) 打印结果,其中 chr 是当前正在循环中的字符,然后退出循环。

【讨论】:

  • 所以你的意思是当它在字符串上的循环不正确时,我想我理解你的意思,但是使用 indexOf 将如何找到它失败的地方,我对那个@Alilssa 有点困惑
  • 当你在循环并且你的代码进入 else 语句时,c++ char in(my_string[i]) 将是不是正确值的聊天,所以通过获取这个 char 的索引你可以知道它停止的地方,然后在这个特定字符的索引上子串你的字符串。
猜你喜欢
  • 2016-01-24
  • 2015-03-30
  • 1970-01-01
  • 2020-02-16
  • 2014-09-19
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多