I'm trying to use regex to check if a number is valid but I'm getting an error and not sure how to write this.
regex e{R"(((^666)|(^900-999))(-*)([^0-6])(-*)(\d{4}))"};
So what I'm trying to say is "check for: a number that is not 666 or from 900-999 then an optional hyphen, a number from 0-6 and an optional hyphen, then 4 digits.
I tried running this but no matter what I put, the console tells me that my input is always incorrect.
Any help would be appreciated.
This isn't a task that regular expressions are well suited for.
If you want to check for a number that isn't equal to 666 or in the range 900-999, you need to decompose that into the following ugly set of cases:
As a regular expression, that'd be (with some spaces added for clarity):
(
[0-578][0-9][0-9]
|
6[0-57-9][0-9]
|
66[0-57-9]
)
As you can see, this isn't a reasonable way to go about this. Reserve the regular expression for checking the format, then check logical issues (like "can't be 666 or 900-999") separately, in code. As a bonus, this will allow you to give precise error messages for these logical issues, instead of lumping them under a generic "wrong format" error.
What you want, if you decide to do this with only regular expressions, is a negative lookahead. However, this is not part of some regular expression specifications. Within C++, the only compatible syntax option is std::regex_constants::ECMAScript, which happens to be the default when constructing a std::regex.
The negative lookahead is represented by (?!<expr>), where there will be no match if <expr> matches at that point. For example, (?!666) would disallow the literal string "666" from being present at that point in the matching.
We can use this to fix your original regular expression. Note that I put in some non-exhaustive tests for this as well.
std::regex e{R"((?!666|9\d{2})\d+-?[0-6]-?\d{4})"};
Let's decompose this:
(?!666|9\d{2}) - We have a negative lookahead that prevents this from matching when 666 or a three-digit number starting with 9 appears at the beginning.
\d+ - Here is the number we are matching that cannot be 666 or in the 900s. I chose to match any number of digits here because the question didn't specify otherwise.
?- - An optional hyphen. Your question contains -*, which is zero or more hyphens.
[0-6] - A single digit from 0 to 6. Your question has a leading caret, which has the effect of negating the character set. This would allow any character except for 0-6.
-? - Another optional hyphen.
\d{4} - A four-digit number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With