0

I have a simple regex express to validate user input is integer. In C# project, i see it validates correctly. Below is my code in 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!");

But in C++ i see it validates in correctly. It only validates correctly string with lengh is 1. Below is my code in 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!";

Please help. It's C++ problem or my problem?

1 Answers1

1

According to MSDN, the C# method bool Regex.IsMatch(String)

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

So it will return true if there is at least one digit in the input string.


C++ std::regex_match

Determines if the regular expression matches the entire target character sequence

So the whole input string must contains digits to pass the regex.

To validate string with integer of any length in C++ you have to use this regex:

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

or

 std::regex int_regex("\\d+");
ikleschenkov
  • 972
  • 5
  • 11