how to write this regular expression? - c#

an 20 - 24 char long alphanumeric string with no spaces and no symbols that has at least 2 digits
AAAAAAAAAAAAAAAAAAAA - not valid
AAAAAA0AAAAAAAAA0AAA - valid
AAAAAA01AAAAAAAAA0AAA - valid
AAAAAA0AAAAAAAAA0AAA# - not valid

I think this is only possible with look-ahead assertion:
^(?=[a-zA-Z\d]{20,24}$)[a-zA-Z]*\d[a-zA-Z]*\d[a-zA-Z\d]*$
The look-ahead assertion ((?=[a-zA-Z\d]{20,24}$)) checks if the string has the expected form (20–24 alphanumeric characters). And the second part ([a-zA-Z]*\d[a-zA-Z]*\d[a-zA-Z\d]*) checks if it contains at least two digits.

I think that this is the simplest pattern: First make a positive lookahead to check that there are at least two digits, then match 20-24 alphanumeric characters:
^(?=.*\d.*\d)[A-Za-z\d]{20,24}$

I'm going to be abstract because this sounds like homework (if it is, please tag it as such).
You can restrict the number of times a pattern matches with {min,max}
You can restrict which characters match with [charlist]
You can impose additional restrictions with what's called zero-width positive lookahead (there's also a negative form). The syntax varies, so check the docs for your environment.
Update your question (& tags) if you need more help.

Gumbo has a correct expression for the requirements.
It could be shortened, but his was more clear and probably faster than the short version.
var rX=/^(?=[a-zA-Z\d]{20,24}$)([a-zA-Z]*\d){2,}/

in JS (not confident enough with C# syntax):
if (str.length >= 20 && str.length <= 24 && /([a-z]*[0-9]){2}[a-z0-9]*/i.test(str)) {
// match found
}

Basically the same idea as Gumbo just a little shorter:
^(?=[\w\d]{20,24}$)[\w]*\d[\w]*\d[\w\d]*$

Related

Regex IsMatch aways returns false [duplicate]

I have a regex
/^([a-zA-Z0-9]+)$/
this just allows only alphanumerics but also if I insert only number(s) or only character(s) then also it accepts it. I want it to work like the field should accept only alphanumeric values but the value must contain at least both 1 character and 1 number.
Why not first apply the whole test, and then add individual tests for characters and numbers? Anyway, if you want to do it all in one regexp, use positive lookahead:
/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/
This RE will do:
/^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i
Explanation of RE:
Match either of the following:
At least one number, then one letter or
At least one letter, then one number plus
Any remaining numbers and letters
(?:...) creates an unreferenced group
/i is the ignore-case flag, so that a-z == a-zA-Z.
I can see that other responders have given you a complete solution. Problem with regexes is that they can be difficult to maintain/understand.
An easier solution would be to retain your existing regex, then create two new regexes to test for your "at least one alphabetic" and "at least one numeric".
So, test for this :-
/^([a-zA-Z0-9]+)$/
Then this :-
/\d/
Then this :-
/[A-Z]/i
If your string passes all three regexes, you have the answer you need.
The accepted answers is not worked as it is not allow to enter special characters.
Its worked perfect for me.
^(?=.*[0-9])(?=.*[a-zA-Z])(?=\S+$).{6,20}$
one digit must
one character must (lower or upper)
every other things optional
Thank you.
While the accepted answer is correct, I find this regex a lot easier to read:
REGEX = "([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*"
This solution accepts at least 1 number and at least 1 character:
[^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))
And an idea with a negative check.
/^(?!\d*$|[a-z]*$)[a-z\d]+$/i
^(?! at start look ahead if string does not
\d*$ contain only digits | or
[a-z]*$ contain only letters
[a-z\d]+$ matches one or more letters or digits until $ end.
Have a look at this regex101 demo
(the i flag turns on caseless matching: a-z matches a-zA-Z)
Maybe a bit late, but this is my RE:
/^(\w*(\d+[a-zA-Z]|[a-zA-Z]+\d)\w*)+$/
Explanation:
\w* -> 0 or more alphanumeric digits, at the beginning
\d+[a-zA-Z]|[a-zA-Z]+\d -> a digit + a letter OR a letter + a digit
\w* -> 0 or more alphanumeric digits, again
I hope it was understandable
What about simply:
/[0-9][a-zA-Z]|[a-zA-Z][0-9]/
Worked like a charm for me...
Edit following comments:
Well, some shortsighting of my own late at night: apologies for the inconvenience...
The - incomplete - underlying idea was that only one "transition" from a digit to an alpha or from an alpha to a digit was needed somewhere to answer the question.
But next regex should do the job for a string only comprised of alphanumeric characters:
/^[0-9a-zA-Z]*([0-9][a-zA-Z]|[a-zA-Z][0-9])[0-9a-zA-Z]*$/
which in Javascript can be furthermore simplified as:
/^[0-9a-z]*([0-9][a-z]|[a-z][0-9])[0-9a-z]*$/i
In IMHO it's more straigthforward to read and understand than some other answers (no backtraking and the like).
Hope this helps.
If you need the digit to be at the end of any word, this worked for me:
/\b([a-zA-Z]+[0-9]+)\b/g
\b word boundary
[a-zA-Z] any letter
[0-9] any number
"+" unlimited search (show all results)

Regex Numbers with 0 or 1 - follow by numbers

I'm trying to match this string, but I'm not getting to work. The string can only have either numbers or numbers with 1 dash follow by another set of numbers.
My Regex Formula:
^([0-9]*|[0-9]*\-{1}[0-9]*)$
EX:
This Pass
123
This pass
123-123
This should fail, but it's passing
123-
This should be the simplest and most efficient way of doing it:
^\d+(?:-\d+)?$
^[0-9]+(?:-[0-9]+)?$*
\d is a character set available in most regex flavors that represents [0-9]. It's a more concise way of matching numerals, but if you prefer [0-9] you can just use that instead.
Note that your original pattern and the patterns offered by others as answers here included the quantifier {1} after the hyphen. This should be avoided, as it's always redundant. A single character without a quantifier is equivalent to the same character followed by {1}.
*Edit: Wiktor brought up something I wasn't aware of. In certain regex flavors, \d includes all unicode digits rather than just the numerals 0 through 9. If this is an issue, you can just use the pattern ^[0-9]+(?:-[0-9]+)?$
You're very close!
The * quantifier matches 0 or more digits.
What you're looking for is the + quantifier which matches 1 or more digits.
Modifying your example:
^([0-9]*|[0-9]+\-{1}[0-9]+)$
Will match either nothing, a single number, or a number-number
You need to understand what the different parts of your regular expression are doing. The * symbolizes zero or any number of some symbol, in your case a number.
If you want at least one number after the dash use + instead of the star.
^([0-9]*|[0-9]*\-{1}[0-9]+)$
^[0-9]+(-[0-9]+)*$
^[0-9]+ starts with one or more numbers
(-[0-9]+)* zero or one occurance of a dash followed by a number with length of 1 or more
For the fun here are some regex-free answers. I find them easier to read.
If -123 and 123--123 are not allowed:
s.Split('-').All(x => x != string.Empty && x.All(char.IsDigit));
Foreach element between -, we check that this element is not empty and made of number only.
If -123 and 123--123 are allowed:
!s.EndsWith("-") && s.All(c => c == '-' || char.IsDigit(c));
Check that a string s does not end with - and that s is made of - and numbers only.
Try it online!
Note that char.IsDigit will allow ๔๕๖๗๘๙໐໑-௫௬௭௮. If you don't want to match this replace char.IsDigit() with IsDigit():
public static bool IsDigit(char c) => c >= '0' && c <= '9';

Regex to validate a number for length and start digits

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.

C# Regex Validation

Can someone please validate this for me (newbie of regex match cons).
Rather than asking the question, I am writing this:
Regex rgx = new Regex (#"^{3}[a-zA-Z0-9](\d{5})|{3}[a-zA-Z0-9](\d{9})$"
Can someone telll me if it's OK...
The accounts I am trying to match are either of:
1. BAA89345 (8 chars)
2. 12345678 (8 chars)
3. 123456789112 (12 chars)
Thanks in advance.
You can use a Regex tester. Plenty of free ones online. My Regex Tester is my current favorite.
Is the value with 3 characters then followed by digits always starting with three... can it start with less than or more than three. What are these mins and max chars prior to the digits if they can be.
You need to place your quantifiers after the characters they are supposed to quantify. Also, character classes need to be wrapped in square brackets. This should work:
#"^(?:[a-zA-Z0-9]{3}|\d{3}\d{4})\d{5}$"
There are several good, automated regex testers out there. You may want to check out regexpal.
Although that may be a perfectly valid match, I would suggest rewriting it as:
^([a-zA-Z]{3}\d{5}|\d{8}|\d{12})$
which requires the string to match one of:
[a-zA-Z]{3}\d{5} three alpha and five numbers
\d{8} 8 digits or
\d{12} twelve digits.
Makes it easier to read, too...
I'm not 100% on your objective, but there are a few problems I can see right off the bat.
When you list the acceptable characters to match, like with a-zA-Z0-9, you need to put it inside brackets, like [a-zA-Z0-9] Using a ^ at the beginning will negate the contained characters, e.g. `[^a-zA-Z0-9]
Word characters can be matched like \w, which is equivalent to [a-zA-Z0-9_].
Quantifiers need to appear at the end of the match expression. So, instead of {3}[a-zA-Z0-9], you would need to write [a-zA-Z0-9]{3} (assuming you want to match three instances of a character that matches [a-zA-Z0-9]

regular expression to match a pattern

I need a regular expression for c# which can match following pattern
abc1abcd
1abcdefg
abcdefg1
basically my expression should have at least one number and min size is 8 char including number. If possible explain the regex also.
I'd probably check with two statements. Just check the length eg
string.Length > 7
and then make sure it this regex can find a match...
[0-9]
You can use a look-ahead assertion to verify the length, and then search forward for a digit, thus:
(?=.{8}).*[0-9]
We look-ahead for 8 characters, and if that is successful, then we actually attempt to match "anything, followed by a digit".
But really, don't do this. Just check the length explicitly. It's much clearer.
Your regular expression pattern should just be: \d+ (match 1 or more numbers). For your example, it's probably best to not determine minimum length using regex since all you care about is that it has at least 1 number and is at least than 8 characters
Regex regEx = new Regex(#"\d+");
isValid = regEx.Match(myString).Success && myString.Length >= 8;
The pattern \d is just the same as [0-9] and the + symbol means at least one of. The # symbol in front of the string is so that it what try to escape \d.
As mentioned by El Ronnoco in the comments, just \d would match your requirement. Knowing about \d+ is useful for more complicated patterns where you want a few numbers in between some strings,etc.
Also: I've just read something that I didn't know. \d matches any character in the Unicode number, decimal digit category which is a lot more than just [0-9]. Something to be aware of if you just want any number. Otherwise El Ronnoco's answer of [0-9] for your pattern is sufficient.

Categories