This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 7 years ago.
I have the following rule:
Don't allow numbers of any sequence with 4 or more 0s at the beginning.
So this number:
0000438967
will fail validation (4 zeros)
But this number:
0004389678 (3 zeros)
Will pass validation.
the reason for this question was I needed verification on whether I was doing it correctly as, when checking in online Regex validators, I was getting mixed verification results. I know it sounds like a simple question but verification from others is important.
thanks
Russ
Unbelievable amount of trial & error answers on this question! The solution is as simple as this:
string number = "0000438967";
bool pass = Regex.IsMatch(number, #"^0{0,3}[1-9]\d*$");
This allows numbers of any length, as long as there is at least one non-zero digit. Replace the last asterisk by {n} or {m,n} to also check length.
Of course, you may want to construct a Regex instance for repeated use.
If you also need the numeric value, you can immediately parse it if pass == true:
int value = Int32.Parse(number);
Of course, depending on the maximum length you want to allow you might need an Int64... but anyway you must provide a maximum length in the regex or the Parse can cause an overflow.
If you must use regular expression, you can use a Negative Lookahead assertion.
^(?!0000)\d+$
Lookarounds are zero-width assertions. They don't consume any characters on the string. The point of zero-width is the validation to see if a regex can or cannot be matched looking ahead or looking back from the current position, without adding them to the overall match.
Example:
Regex.IsMatch("0438967", #"^(?!0000)\d+$"); // True
Regex.IsMatch("004389678", #"^(?!0000)\d+$"); // True
Regex.IsMatch("000438967", #"^(?!0000)\d+$"); // True
Regex.IsMatch("00004389678", #"^(?!0000)\d+$"); // False
Regex.IsMatch("00000438967", #"^(?!0000)\d+$"); // False
Regex.IsMatch("000000438967", #"^(?!0000)\d+$"); // False
Zero to three zeroes followed optionally by a nonzero number followed by any number of numbers:
0{0,3}([1-9][0-9]*)?
It should accept:
000
While rejecting any number with 4+ zeroes at the beginning.
Don't use a lookahead/behind for this as that triggers backtracking.
EDIT: if your matching function does not perform an exact match then you'll need to do:
^0{0,3}([1-9][0-9]*)?$
Please try this..
string myString = "00011111";//Valid
if (Regex.IsMatch(myString, #"^[0-9]{3}[1-9]+$"))
{
Console.WriteLine("Valid");
Console.ReadKey();
}
Assuming you accept no zeros at all and at least one non-zero digit, here is your regex:
string str = "001";
bool passed = Regex.IsMatch(str, #"^0{0,3}[1-9]\d*$");
Explanation: Regex check for 0 to 3 '0's, then for one non-'0' digits and then for zero or more of any digits.
if "000" is acceptable, then negative look-ahead solution from #hwnd is more elegant. I would just use 0{4} instead of 0000.
You can use Regex to find out the string is valid or not
!Regex.Match(str, #"^0000(\d+)", RegexOptions.IgnoreCase).Success
here is working sample rextester
Related
Is there any regex for validating a serial number input, the range should be between DC0001000 to DC9999999.
I searched through the internet but I didn't find any solution for this validating serial number regex.
The Prefix DC is mandatory and the next 7 digits must be in the range (0001000 - 9999999).
I tried with this regex -
[DC]{1}\d{7}[0001000-9999999]
but it didn't work for me.
Is there a regex that will match this?
If we're going for the shortest one, how about this?
DC(?!0000)\d{7}
This should do it:
^DC(?=\d{0,3}[1-9])\d{7}$
It checks that the string starts with DC and then a positive look ahead checks that one of the following four digits isn't zero - and then 7 digits.
Check it out here at regex101.
Edit simplified (removed the unnecessary first test)
you are looking look ahead regular expressions. These expressions wont change reg ex pointer. so that pointer can remain at -1 and you can visit the entire string "n" of times.
?=(expression1)?=(expression2)...?=(expression_n)
Also useful in password policy verification.
Hi try this for RegExp beginers
([D]{1}[C]{1}[0]{3})?([D]{1}[C]{1}[0]{3}[1-9]{1}[0-9]{3})|([D]{1}[C]{1}[1-9]{1})?([D]{1}[C]{1}[1-9]{1}[0-9]{6})|([D]{1}[C]{1}[0-9]{1}[1-9]{1})?([D]{1}[C]{1}[0-9]{1}[1-9]{1}[0-9]{5})|([D]{1}[C]{1}[0-9]{2}[1]{1})?([D]{1}[C]{1}[0-9]{2}[1]{1}[0-9]{4})
I'm stuck on this problem. I have an input field for a zip code, however, our database has a lot of records where the zip code is 0. I currently have a regular expression set on the field to ensure that the zip is either empty or is a 5 digit value.
Because this however, if you go to update a record that has the value set to "0", it triggers a validation message because it is not an empty string or a 5 digit string. I want to make it be able to accept all three of these states (empty, "0" or a 5 digit number).
(^\s{0,5}$)|(^\d{5}$) - This is what I've been using for the empty or 5 digit number, it seems to work fine.
(^?:(\s{0}$)|(^?:(0){1}$|\d{5})$) - I've tried this for the empty, "0" or 5 digit number, but it doesn't work. I really have next to no clue what's going on, I barely understand regular expressions. Help would be appreciated, thanks!
I would go with:
(^([0]|[0-9]{5})$)
Where the input is 0 or any 5 number combination.
As pointed out in the comment, regex is for matching and you can't match when there is nothing
Dont use Regex to check for empty string:
if String.IsNullOrEmpty(myString)
{
// String is empty, do something.
Console.WriteLine("No string here!");
}
else
{
// Do Regex here
}
You will always want to match the start and end of the string, so you won't need these in the Regex groups. As for the shorthand character '\s', this merely represents a space.
What you will want to match:
Empty string
Single zero
Five-digit number
To this end, the following should hopefully work:
^(\s{0}|0|\d{5})$
Use this regexrp (^$)|0|\d{5}
but string.IsNullOrEmpty() and int.Parse() are preferred.
I'm looking for a regex that will validate a number.
One part is easy ^(\d{5,9})$ the string representing the number must be 5 to 9 digits.
Part 2 I don't know how: It must NOT start with 9999
How can I add that part?
This do the job:
^(?!9999)\d{5,9}$
(?!....) is a negative lookahead and means "not followed by"
You want a negative-lookahead assertion, anchored at start of string:
Regex rx = new Regex( #"^(?!9999)\d{5,9}$" ) ;
I would recommend that you use your programming language's normal string functions to extract the first four characters of the string and compare them to "9999". This will be more efficient than a negative lookahead assertion, and also easier to read.
I suppose there could be some special circumstances where it needs to conform to the regex format. If this is the case, then the other answers have what you need. But I think it's good to realize not everything involving pattern matching has to use a regular expression.
What is the regular expression for a 10 digit numeric number (no special characters and no decimal).
Use this regular expression to match ten digits only:
#"^\d{10}$"
To find a sequence of ten consecutive digits anywhere in a string, use:
#"\d{10}"
Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits and not more you can use negative lookarounds:
#"(?<!\d)\d{10}(?!\d)"
Use the following pattern.
^\d{10}$
This works for me:
only 10 digit number is accepted.
^[0-9]{10}$
\d{10}
I believe that should do it
An example of how to implement it:
public bool ValidateSocialSecNumber(string socialSecNumber)
{
//Accepts only 10 digits, no more no less. (Like Mike's answer)
Regex pattern = new Regex(#"(?<!\d)\d{10}(?!\d)");
if(pattern.isMatch(socialSecNumber))
{
//Do something
return true;
}
else
{
return false;
}
}
You could've also done it in another way by e.g. using Match and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.
Use this:
\d{10}
I hope it helps.
I'm not sure how to accomplish this with a regular expression (or if I can; I'm new to regex). I have an angle value the user will type in and I'm trying to validate the entry. It is in the form degrees-minutes-seconds. The problem I'm having, is that if the user mistypes the seconds portion, I have to catch that error, but my match for degrees-minutes is a success.
Perhaps the method will explain better:
private Boolean isTextValid(String _angleValue) {
Regex _degreeMatchPattern = new Regex("0*[1-9]");
Regex degreeMinMatchPattern = new Regex("(0*[0-9]-{1}0*[0-9]){1}");
Regex degreeMinSecMatchPattern = new Regex("0*[0-9]-{1}0*[0-9]-{1}0*[0-9]");
Match _degreeMatch, _degreeMinMatch, _degreeMinSecMatch;
_degreeMinSecMatch = degreeMinSecMatchPattern.Match(_angleValue);
if (_degreeMinSecMatch.Success)
return true;
_degreeMinMatch = degreeMinMatchPattern.Match(_angleValue);
if (_degreeMinMatch.Success)
return true;
_degreeMatch = _degreeMatchPattern.Match(_angleValue);
if (_degreeMatch.Success)
return true;
return false;
}
}
I want to check for degrees-minutes if the degrees-minutes-seconds match is unsuccessful, but only if the user didn't enter any seconds data. Can I do this via regex, or do I need to parse the string and evaluate each portion separately? Thanks.
EDIT: Sample data would be 45-23-10 as correct data. The problem is 45-23 is also valid data; the 0 seconds is understood. So if the user types 45-23-1= on accident, the degreeMinMatchPattern regex in my code will match succesfully, even though it is invalid.
Second EDIT: Just to make it clear, the minutes and second portions are both optional. The user can type 45 and that is valid.
You can specify "this part of the pattern must match at least 3 times" using the {m,} syntax. Since there are hyphens between each component, specify the first part separately, and then each hyphen-digit combination can be grouped together after:
`[0-9](-[0-9]){2,}`
You also can shorten [0-9] to \d: \d(-\d){2,}
First off, a character in a regex is matched once by default, so {1} is redundant.
Second, since you can apparently isolate this value (you prompt for just this value, instead of having to look for it in a paragraph of entered data) you should include ^ and $ in your string, to enforce that the string should contain ONLY this pattern.
Try "^\d{1,3}-\d{1,2}(-\d{1,2})?$".
Breaking it down: ^ matches the beginning of the string. \d matches any single decimal character, and then behind that you're specifying {1,3} which will match a set of one to three occurrences of any digit. Then you're looking for one dash, then a similar decimal pattern but only one or two times. The last term is enclosed in parenthesis so we can group the characters. Its form is similar to the first two, then there's a ? which marks the preceding character group as optional. The $ at the end indicates that the input should end. Given this, it will match 222-33-44 or 222-33, but not 222-3344 or 222-33-abc.
Keep in mind there are additional rules you might want to incorporate. For instance, seconds can be expressed as a decimal (if you want a resolution smaller than one second). You would need to optionally expect the decimal point and one or more additional digits. Also, you probably have a maximum degree value; the above regex will match the maximum integer DMS value of 359-59-59, however it will also match 999-99-99 which is not valid. You can limit the maximum value using regex (for example "(3[0-5]\d|[1-2]\d{2}|\d{1,2})" will match any number from 0 to 359, by matching a 3, then 0-5, then 0-9, OR any 3-digit number starting with 1 or 2, OR any two-digit number), but as the example shows the regex will get long and messy, so document it well in code as to what you're doing.
Maybe you would do better to just parse the input out and check is piece separately.
I'm not sure I understand correctly, but I think
(?<degrees>0*[0-9])-?(?<minutes>0*[0-9])(?:-?(?<seconds>0*[0-9]))?$
might work.
But this is quite ambiguous; also I'm wondering why you're only allowing single-digit degree/minute/second values. Please show some examples you do and don't want to match.
Maybe you should to try something like this and test for empty/invalid groups:
Regex degrees = new Regex(
#"(?<degrees>\d+)(?:-(?<minutes>\d+))?(?:-(?<seconds>\d+))?");
string[] samples = new []{ "123", "123-456", "123-456-789" };
foreach (var sample in samples)
{
Match m = degrees.Match(sample);
if(m.Success)
{
string degrees = m.Groups["degrees"].Value;
string minutes = m.Groups["minutes"].Value;
string seconds = m.Groups["seconds"].Value;
Console.WriteLine("{0}°{1}'{2}\"", degrees,
String.IsNullOrEmpty(minutes) ? "0" : minutes,
String.IsNullOrEmpty(seconds) ? "0" : seconds
);
}
}