<分区>
<分区>
我有一个简单的正则表达式来验证用户输入是整数。在 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/