c# Regex 0-9 and dash - c#

I have a credit card number that I need to check if it has digits from 0 - 9 and also any dashes.
I have the following:
Match match = Regex.Match(CardNumber, "[0-9-]");
if (match.Success)
{
}
It works but wondering if I missed anything that may not make it work.
Thanks

Right now it only checks if there is at least one digit or dash inside the string CardNumber, so it would return True for the string "hello0!".
If you want to validate the string so it only consists of digits and dashes, you need to use
Match match = Regex.Match(CardNumber, #"^[0-9-]*$");

As a small note to what #Tim wrote, his regex will match -12--34-. Probably what you want is:
^([0-9]+-)*[0-9]+$
This will require at least a digit. If you want the empty string to match, use
^([0-9]+-)*[0-9]*$
(0 or more "groups" of one or more digits plus a - and a final "group" of digits)

Related

C# Regex match only if one group of numbers is found in string

I'm trying to come up with a regex to deal with a general scenario to capture a number from a string where the number may have one or more non-numeric characters pre/post-fixed to it.
The number can contain zero or one decimal or comma.
If the string contains multiple "sets" of consecutive digits separated by non-digits I would like the regex to fail ("sets" is probably not the correct terminology).
As an example the following inputs would succeed with a match:
abc12.00xyz would match 12.00
0.1$ would be valid and match 0.1
.01 would be valid and match .01
123abc would be valid and match 123
abc123 would be valid and match 123
These inputs would fail to match:
abc12.00xyz322 would fail due to the second "set" of digits, 322 in this example
12t2 would fail due to having two separate "sets" of digits
I've tried many permutations and I'm not making much headway. This is the closest I've come to so far. It matches on the numbers correctly, excluding the non-digits from the match, but it includes all "sets" of numbers in the string.
([\d]*[.,])?[\d]+
Any suggestions would be appreciated.
You can use a capture group:
^[^0-9\r\n]*?([0-9]*\.?[0-9]+)[^0-9\r\n]*$
^ Start of string
[^0-9\r\n]* Optionally match any char except a digit or a newline, as few as possible
([0-9]*\.?[0-9]+) Capture group 1, match optional digits, optional comma and 1+ digits
[^0-9\r\n]* Optionally match any char except a digit or a newline
$ End of string
See a .NET regex demo (Click on the Table tab to see the capture group values)

Writing a proper regex to allow number and only combinations of letters and numbers mixed up

I have a string example which looks like this:
51925120851209567
The length of the string and numbers may vary, however I want to only enable the string to contain just either numbers, or for it to be a combination of letters and numbers. For example a valid one would be something like this:
B0031Y4M8S // contains combination of letters and numbers without white space
Invalid regex would be:
Does not apply // this one contains white spaces and has only letters
To summarize things up, the regex should allow only these combinations:
51925120851209567 // contains only numbers and is valid
B0031Y4M8S // contains combination of numbers and letters and is valid as well
Everything else is invalid...
The current solution that I have covers only for the string to be a set of integers and nothing else... However I'm not really sure how to filter out combination of numbers and letters without white spaces and special charachters to be valid as well for the regex?
Regex regex = new Regex("^[0-9]+$");
if (regex.IsMatch(parameter))
{
// allow if statement to pass if the regex matches
}
Can someone help me out ?
You may use
^(?![A-Za-z]+$)[0-9A-Za-z]+$
It matches 1+ alphanumeric chars but will fail a match if all string consists of just letters.
Details
^ - start of a string
(?![A-Za-z]+$) - a negative lookahead that fails the match if there are 1+ ASCII letters followed with the end of string immediately to the right of the current location
[0-9A-Za-z]+ - 1+ ASCII letters
$ - end of string.
See the regex demo.
#The fourth bird's answer will almost get you there. I'm no regex expert, but an easy way to get you what you want would be to use:
Regex regex = new Regex("^[a-zA-Z0-9]+$");
This will get you the first level of exclusion. If it passes that, then check with:
Regex regex = new Regex("^[a-zA-Z]+$");
If it matches that, then you know it's only alphabetical characters and you can skip it. I'm sure there's a better way to code golf this one out, but this should work for now if you're in a crunch.

Regex needs to match alphanumeric string with min of one number look ahead only checks second postion

I have been trying to solve this problem for a bit now and have had to turn to asking you fine people.
I have found the following regex pattern many times and from what I have read it should work but doesn't actually seem to work
\b(?=.\d)(?i)[a-z\d]{3,}\b
The problem with it is that if there is a letter at the second position of the string it fails even if there is a digit in the string.
So 60B15H passes like it should be but 6D15H fails which is not what I want
My requirements for the regex is that the string needs to be alphanumeric and contain at least one number in any position it can be all digits. It just cannot contain all letters or any special characters. It needs to be minimum of 3 characters long.
You can use
(?i)\b(?=[a-z]*\d)[a-z\d]{3,}\b
^^^^^^^^^^^^
You need to tell the regex engine to check a digit after any letters. The (?=[a-z]*\d) lookahead is executed once after each leading word boundary \b and makes sure there is at least one digit after a sequence of letters.
See regex demo
Why use regex when you can get the same with simple code:
public static bool isValid(string input)
{
if(input.Length < 3 || input.All(c => char.IsLetter(c)))
{
return false;
}
return input.All(c => char.IsLetterOrDigit(c));
}

Match at least one character and one number, regardless of order, with no suffix?

I need a RegEx that fulfills this statement:
There is at least one character and one digit, regardless of order, and there is no suffix (i.e. domain name) at the end.
So I have this test list:
ra182
jas182
ra1z4
And I have this RegEx:
[a-z]+[0-9]+$
It's matching the first two fully, but it's only matching the z4 in the last one. Though it makes sense to me why it's only matching that piece of the last entry, I need a little help getting this the rest of the way.
You can check the first two conditions with lookaheads:
/^(?=.*[a-z])(?=.*[0-9])/i
... and if the third one is just about the absence of ., it's simple to check too:
/^(?=.*[a-z])(?=.*[0-9])[^.]+$/i
But I'd probably prefer to use three separate tests instead: with first check for symbols (are you sure it's enough to check just for a range - [a-z] - and not for a Unicode Letter property?), the second for digits, and the final one for this pesky dot, like this:
if (Regex.IsMatch(string, "[a-zA-Z]")
&& Regex.IsMatch(string, "[0-9]")
&& ! Regex.IsMatch(string, #"\.") )
{
// string IS valid, proceed
}
The regex in the question will try to match one or more symbols, followed by one or more digits; it obviously will fail for the strings like 9a.
I suggest to use
Match match = Regex.Match(str, #"^(?=.*[a-zA-Z])(?=.*\d)(?!.*\.).*");
or
Match match = Regex.Match(str, #"^(?=.*[a-zA-Z])(?=.*\d)(?!.*[.]).*");
or
Match match = Regex.Match(str, #"^(?=.*[a-zA-Z])(?=.*\d)[^.]*$");
or
Match match = Regex.Match(str, #"^(?=.*[a-zA-Z])[^.]*\d[^.]*$");
if (match.Success) ...
You need to match alphanumeric strings that have at least one letter and one number? Try something like this:
\w*[a-z]\w*[0-9]\w*
This will make sure you have at least one letter and one number, with the number after the letter. If you want to take into account numbers before letters, just use the corresponding expressiong (numbers before letters) and | the two.

Regular expression for accepting alphanumeric characters (6-10 chars) .NET, C#

I am building a user registration form using C# with .NET.
I have a requirement to validate user entered password fields.
Validation requirement is as below.
It should be alphanumeric (a-z , A-Z , 0-9)
It should accept 6-10 characters (minimum 6 characters, maximum 10 characters)
With at least 1 alphabet and number (example: stack1over)
I am using a regular expression as below.
^([a-zA-Z0-9]{6,10})$
It satisfies my first 2 conditions.
It fails when I enter only characters or numbers.
Pass it through multiple regexes if you can. It'll be a lot cleaner than those look-ahead monstrosities :-)
^[a-zA-Z0-9]{6,10}$
[a-zA-Z]
[0-9]
Though some might consider it clever, it's not necessary to do everything with a single regex (or even with any regex, sometimes - just witness the people who want a regex to detect numbers between 75 and 4093).
Would you rather see some nice clean code like:
if not checkRegex(str,"^[0-9]+$")
return false
val = string_to_int(str);
return (val >= 75) and (val <= 4093)
or something like:
return checkRegex(str,"^7[5-9]$|^[89][0-9]$|^[1-9][0-9][0-9]$|^[1-3][0-9][0-9][0-9]$|^40[0-8][0-9]$|^409[0-3]$")
I know which one I'd prefer to maintain :-)
Use positive lookahead
^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{6,10}$
Look arounds are also called zero-width assertions. They are zero-width just like the start and end of line (^, $). The difference is that lookarounds will actually match characters, but then give up the match and only return the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not.
The syntax for look around:
(?=REGEX) Positive lookahead
(?!REGEX) Negative lookahead
(?<=REGEX) Positive lookbehind
(?<!REGEX) Negative lookbehind
string r = #"^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]{6,10}$";
Regex x = new Regex(r);
var z = x.IsMatch(password);
http://www.regular-expressions.info/refadv.html
http://www.regular-expressions.info/lookaround.html

Categories

Resources