0

我只是想弄乱并熟悉在 C++ 中使用正则表达式。假设我希望用户输入以下内容:###-$$-###,使 #=0-9 之间的任何数字和 $=0-5 之间的任何数字。这是我完成此任务的想法:

regex rx("[0-9][0-9][0-9]""\\-""[0-5][0-5]")

这不是确切的代码,但这是检查用户输入是否是有效数字字符串的一般想法。但是,假设我不允许以 0 开头的数字,因此:099-55-999 是不可接受的。我怎样才能检查类似的东西并输出无效?谢谢

4

3 回答 3

4
[0-9]{3}-[0-5]{2}-[0-9]{3}

matches a string that starts with three digits between 0 and 9, followed by a dash, followed by two digits between 0 and 5, followed by a dash, followed by three digits between 0 and 9.

Is that what you're looking for? This is very basic regex stuff. I suggest you look at a good tutorial.

EDIT: (after you changed your question):

[1-9][0-9]{2}-[0-5]{2}-[0-9]{3}

would match the same as above except for not allowing a 0 as the first character.

于 2011-12-02T21:52:19.403 回答
1
std::tr1::regex rx("[0-9]{3}-[0-5]{2}-[0-9]{3}");

Your talking about using tr1 regex in c++ right and not the managed c++? If so, go here where it explains this stuff.

Also, you should know that if your using VS2010 that you don't need the boost library anymore for regex.

于 2011-12-02T21:55:16.023 回答
1

Try this:

#include <regex>
#include <iostream>
#include <string>

int main()
{
    std::tr1::regex rx("\\d{3}-[0-5]{2}-\\d{3}");
    std::string s;
    std::getline(std::cin,s);
    if(regex_match(s.begin(),s.end(),rx))
    {
        std::cout << "Matched!" << std::endl;
    }
}

For explanation check @Tim's answer. Do note the double \ for the digit metacharacter.

于 2011-12-02T21:56:04.933 回答