繁体   English   中英

验证字符串的整数部分

[英]Validating integer part of an string

我有一个文本文件,需要将每一行转换为整数。

这些行可以以“#”开头来表示注释。 此外,在数据之后它也可能是内联注释......再次由“#”表示

所以我有下面的例子:

QString time = "5000 #this is 5 seconds";  // OK      
QString time = "  5000 # this is 5 seconds"; // OK..free spaceis allowed at start        
QString time = "5000.00 #this is 5 seconds"; // invalid...no decimal 
QString time = "s5000 # this is 5 seconds"; // invalid...does not start with numerical character

我该如何处理这些情况? 我的意思是在上面的所有 4 个示例中,除了最后两个我需要提取“5000”。 如何找出最后一个无效?

所以我的意思是处理这个任务的最好的防故障代码是什么?

您可以使用此正则表达式来验证和提取第一个分组模式中的数字,该分组模式将捕获您的号码,

^\s*(\d+)\b(?!\.)

解释:

  • ^ - 字符串的开始
  • \\s* - 允许数字前的可选空格
  • (\\d+) - 捕获数字并将其放在第一个分组模式中
  • \\b - 确保数字在较大的文本中不部分匹配,因为前面存在负面展望
  • (?!\\.) - 如果数字后面有小数,则拒绝匹配

演示1

如果只有最后一个无效,您可以使用此正则表达式从前三个条目中捕获数字,

^\s*(\d+)

演示2

另一个使用std::regex例子。 QString转换为string_view留给读者作为练习。

#include <regex>
#include <string_view>
#include <iostream>
#include <string>
#include <optional>

std::optional<std::string> extract_number(std::string_view input)
{
    static constexpr char expression[] = R"xx(^\s*(\d+)\s*(#.*)?$)xx";
    static const auto re = std::regex(expression);

    auto result = std::optional<std::string>();
    auto match = std::cmatch();
    const auto matched = std::regex_match(input.begin(), input.end(), match, re);
    if (matched)
    {
        result.emplace(match[1].first, match[1].second);
    }

    return result;
}

void emit(std::string_view candidate, std::optional<std::string> result)
{
    std::cout << "offered: " << candidate << " - result : " << result.value_or("no match") << '\n';
}

int main()
{
    const std::string_view candidates[] = 
    {
"5000 #this is 5 seconds",
"  5000 # this is 5 seconds",
"5000.00 #this is 5 seconds",
"s5000 # this is 5 seconds"
    };

    for(auto candidate : candidates)
    {
        emit(candidate, extract_number(candidate));
    }
}

预期输出:

offered: 5000 #this is 5 seconds - result : 5000
offered:   5000 # this is 5 seconds - result : 5000
offered: 5000.00 #this is 5 seconds - result : no match
offered: s5000 # this is 5 seconds - result : no match

https://coliru.stacked-crooked.com/a/2b0e088e6ed0576b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM