2017-07-26 53 views
0

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

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++问题还是我的问题?

+1

您展示的两个正则表达式是不一样的。 –

+0

这两个正则表达式是不同的,'string_to_validate'的值是什么? –

+0

你试图匹配什么? – revo

回答

0

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

指示在正则表达式 构造函数中指定正则表达式是否发现在指定的输入串的匹配。

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


C++ std::regex_match

确定是否正则表达式匹配整个目标 字符序列

所以整个输入字符串必须包含数字传递正则表达式。

要在C任意长度的整数验证字符串++,你必须使用这个表达式:

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

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

std :: regex_match返回失败,输入字符串为“1”,“11”,“1111”。 –

+0

@PhungTienTrieu,很奇怪。你的测试字符串是否有前/后空格? – ikleschenkov

+0

现在没事了。但你能否请扩展为什么我的原始表达式在C#(System.Text.RegularExpression)中工作,但在C++中不起作用(std :: regex,std :: regex_match)? –