c# - C++ std::regex 错误地验证整数

标签 c# c++ regex

<分区>

我有一个简单的正则表达式来验证用户输入是整数。在 C# 项目中,我看到它验证正确。下面是我在 C# 中的代码:

string string_to_validate = Console.ReadLine();    
Regex int_regex = new Regex("[0-9]");
if (int_regex.IsMatch(string_to_validate))
    Console.WriteLine("Regex is match. Validation is success!");
else
    Console.WriteLine("Regex is not match. Validation is fail!");

但在 C++ 中,我发现它可以正确验证。它只正确验证长度为 1 的字符串。下面是我在 C++ 中的代码:

std::string string_to_validate;
std::cin >> string_to_validate;
std::regex int_regex("[0-9]");
if (std::regex_match(string_to_validate,
                     int_regex))
  std::cout << "Regex is match. Validation is success!";
else
  std::cout << "Regex is not match. Validation is fail!";

请帮忙。是 C++ 的问题还是我的问题?

最佳答案

根据 MSDN , C# 方法 bool Regex.IsMatch(String)

Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.

因此,如果输入字符串中至少有一位数字,它将返回 true


C++ std::regex_match

Determines if the regular expression matches the entire target character sequence

因此整个输入字符串必须包含数字才能通过正则表达式。

要在 C++ 中验证具有任意长度整数的字符串,您必须使用此正则表达式:

 std::regex int_regex("[0-9]+"); // '+' - quantifier '1 or more' items from range [0-9] 

 std::regex int_regex("\\d+");

关于c# - C++ std::regex 错误地验证整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45322599/

上一篇:c++ - 带有 vector 结构的 boost::asio::buffer

下一篇:c++ - 如何在 C++ 代码中搜索所有构造函数?

相关文章:

c++ - 基本的 unix ./语法

regex - PowerShell 将字符串切成两半

java - 如果不使用validation.excludeMethods,则无法在同一操作类下调用两个不同的方法

c++ - 将正则表达式与组相交,如何导出分组位的交集?

c# - DDD、事件存储、UI

c# - 如何从 C# 中的单个完整路径创建多个目录?

c++ - 如何在另一个函数中访问在一个函数中定义和声明的变量?

c# - 如何将项目添加到窗口的上下文菜单中[仅适用于 pdf 文件和 doc 文件]

c# - 如何以编程方式将用户设置为 SharePoint 中的网站集管理员

c++ - 相当于 Direct2D 中的 GDI 笔