regex for at least three letters anywhere in string [duplicate] - c#

I have this regex to allow for only alphanumeric characters.
How can I check that the string at least contains 3 alphabet characters as well.
My current regex,
if(!/^[a-zA-Z0-9]+$/.test(val))
I want to enforce the string to make sure there is at least 3 consecutive alphabet characters as well so;
111 // false
aaa1 // true
11a // false
bbc // true
1a1aa // false

+ means "1 or more occurrences."
{3} means "3 occurrences."
{3,} means "3 or more occurrences."
+ can also be written as {1,}.
* can also be written as {0,}.

To enforce three alphabet characters anywhere,
/(.*[a-z]){3}/i
should be sufficient.
Edit. Ah, you'ved edited your question to say the three alphabet characters must be consecutive. I also see that you may want to enforce that all characters should match one of your "accepted" characters. Then, a lookahead may be the cleanest solution:
/^(?.*[a-z]{3})[a-z0-9]+$/i
Note that I am using the case-insensitive modifier /i in order to avoid having to write a-zA-Z.
Alternative. You can read more about lookaround assertions here. But it may be a little bit over your head at this stage. Here's an alternative that you may find easier to break down in terms of what you already know:
/^([a-z0-9]*[a-z]){3}[a-z0-9]*$/i

This should do the work:
^([0-9]*[a-zA-Z]){3,}[0-9]*$
It checks for at least 3 "Zero-or-more numerics + 1 Alpha" sequences + Zero-or-more numerics.

You want to match zero or more digits then 3 consecutive letters then any other number of digits?
/\d*(?:[a-zA-Z]){3,}\d*/

This is vanilla JS you guys can use. My problem is solved using this.
const str = "abcdggfhf";
const pattern = "fhf";
if(pattern.length>2) {
console.log(str.search(pattern));
}

Related

Search for question mark with Regex in C# [duplicate]

I have a regex that I thought was working correctly until now. I need to match on an optional character. It may be there or it may not.
Here are two strings. The top string is matched while the lower is not. The absence of a single letter in the lower string is what is making it fail.
I'd like to get the single letter after the starting 5 digits if it's there and if not, continue getting the rest of the string. This letter can be A-Z.
If I remove ([A-Z]{1}) +.*? + from the regex, it will match everything I need except the letter but it's kind of important.
20000 K Q511195DREWBT E00078748521
30000 K601220PLOPOH Z00054878524
Here is the regex I'm using.
/^([0-9]{5})+.*? ([A-Z]{1}) +.*? +([A-Z]{1})([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3}) +([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})/
Use
[A-Z]?
to make the letter optional. {1} is redundant. (Of course you could also write [A-Z]{0,1} which would mean the same, but that's what the ? is there for.)
You could improve your regex to
^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})
And, since in most regex dialects, \d is the same as [0-9]:
^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})
But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?
You can make the single letter optional by adding a ? after it as:
([A-Z]{1}?)
The quantifier {1} is redundant so you can drop it.
You have to mark the single letter as optional too:
([A-Z]{1})? +.*? +
or make the whole part optional
(([A-Z]{1}) +.*? +)?
You also could use simpler regex designed for your case like (.*)\/(([^\?\n\r])*) where $2 match what you want.
here is the regex for password which will require a minimum of 8 characters including a number and lower and upper case letter and optional sepecial charactor
/((?=.\d)(?=.[a-z])(?=.*[A-Z])(?![~##$%^&*_-+=`|{}:;!.?"()[]]).{8,25})/
/((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?![~##\$%\^&\*_\-\+=`|{}:;!\.\?\"()\[\]]).{8,25})/

Regular Expression to not allow 3 consecutive characters

I have the following regex:
Regex pattern = new Regex(#"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,20}/(.)$");
(?=.*\d) //should contain at least one digit
(?=.*[a-z]) //should contain at least one lower case
(?=.*[A-Z]) //should contain at least one upper case
[a-zA-Z0-9]{8,20} //should contain at least 8 characters and maximum of 20
My problem is I also need to check if 3 consecutive characters are identical. Upon searching, I saw this solution:
/(.)\1\1/
However, I can't make it to work if I combined it to my existing regex, still no luck:
Regex(#"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,20}$/(.)\1\1/");
What did I missed here? Thanks!
The problem is that /(.)\1\1/ includes the surrounding / characters which are used to quote literal regular expressions in some languages (like Perl). But even if you don't use the quoting characters, you can't just add it to a regular expression.
At the beginning of your regex, you have to say "What follows cannot contain a character followed by itself and then itself again", like this: (?!.*(.)\1\1). The (?! starts a zero-width negative lookahead assertion. The "zero-width" part means that it does not consume any characters in the input string, and the "negative lookahead assertions" means that it looks forward in the input string to make sure that the given pattern does not appear anywhere.
All told, you want a regex like this:
new Regex(#"^(?!.*(.)\1\1)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,20}$")
I solved by using trial and error:
Regex pattern = new Regex(#"^(?!.*(.)\1\1)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,20}$");

Check Formatting of a String

This has probably been answered somewhere before but since there are millions of unrelated posts about string formatting.
Take the following string:
24:Something(true;false;true)[0,1,0]
I want to be able to do two things in this case. I need to check whether or not all the following conditions are true:
There is only one : Achieved using Split() which I needed to use anyway to separate the two parts.
The integer before the : is a 1-3 digit int Simple int.parse logic
The () exists, and that the "Something", in this case any string less than 10 characters, is there
The [] exists and has at least 1 integer in it. Also, make sure the elements in the [] are integers separated by ,
How can I best do this?
EDIT: I have crossed out what I've achieved so far.
A regular expression is the quickest way. Depending on the complexity it may also be the most computationally expensive.
This seems to do what you need (I'm not that good so there might be better ways to do this):
^\d{1,3}:\w{1,9}\((true|false)(;true|;false)*\)\[\d(,[\d])*\]$
Explanation
\d{1,3}
1 to 3 digits
:
followed by a colon
\w{1,9}
followed by a 1-9 character alpha-numeric string,
\((true|false)(;true|;false)*\)
followed by parenthesis containing "true" or "false" followed by any number of ";true" or ";false",
\[\d(,[\d])*\]
followed by another set of parenthesis containing a digit, followed by any number of comma+digit.
The ^ and $ at the beginning and end of the string indicate the start and end of the string which is important since we're trying to verify the entire string matches the format.
Code Sample
var input = "24:Something(true;false;true)[0,1,0]";
var regex = new System.Text.RegularExpressions.Regex(#"^\d{1,3}:.{1,9}\(.*\)\[\d(,[\d])*\]$");
bool isFormattedCorrectly = regex.IsMatch(input);
Credit # Ian Nelson
This is one of those cases where your only sensible option is to use a Regular Expression.
My hasty attempt is something like:
var input = "24:Something(true;false;true)[0,1,0]";
var regex = new System.Text.RegularExpressions.Regex(#"^\d{1,3}:.{1,9}\(.*\)\[\d(,[\d])*\]$");
System.Diagnostics.Debug.Assert(regex.IsMatch(input));
This online RegEx tester should help refine the expression.
I think, the best way is to use regular expressions like this:
string s = "24:Something(true;false;true)[0,1,0]";
Regex pattern = new Regex(#"^\d{1,3}:[a-zA-z]{1,10}\((true|false)(;true|;false)*\)\[\d(,\d)*\]$");
if (pattern.IsMatch(s))
{
// s is valid
}
If you want anything inside (), you can use following regex:
#"^\d{1,3}:[a-zA-z]{1,10}\([^:\(]*\)\[\d(,\d)*\]$"

regex number problem

this is my regex for digital dnumbers:
\d+(.\d+)+(,\d+)
but now i have problem that number 3 or 30 are not valid any more. What must be my regex that also number 3 and 40 will pass.
Thx
\d+(\.\d+)*(,\d+)?
The + in regex means "at least one", whereas the * means "zero or more" and the ? means "either one or none".
Also, you have to escape periods as \. since otherwise the . character is a special character in regex meaning "any single character".
If you want to make sure that the .'s in the number (if present) always separate digits by groups of 3, you could use this (the {x} syntax means "exactly x repetitions"):
\d+(\.\d{3})*(,\d+)?
Or to force thousands separators all the time, you could use this (the {x,y} syntax means "anywhere from x to y repetitions):
\d{1,3}(\.\d{3})*(,\d+)?
\d+((\.\d+)|(,\d+))?
so you want a regex that matches 1 and 3.000 and 3.000,5 ?
If you don't want to capture the result this should do:
[.\d]+(,\d+)?
but keep in mind that this is not very accurat anyway since it also matches 2.0.0,12 and you should also include a plus minus check:
^(\+|-)?[.\d]+(,\d+)?
In C# you could do better with
double result;
bool isDouble = Double.TryParse("3.000,5", Globalisation.CultureInfo.InvariantCulture);
If what you really want is . for thousands separator, and , for the decimal separator, try this:
\d{1,3}(\.\d{3})*(,\d+)?

alphanumeric with at least 1 character

Ok so I finally figured out that I need the following:
So the regular expression has to perform:
alphanumeric
at least 1 letter
must have between 4 and 8 characters (either a letter/digit).
i.e. an alphanumeric string, that must have at least 1 letter, and be between 4-8 in length. (so it can't be just all numbers or just all letters).
can all of this be done in a single regex?
I'm assuming you mean alphaunumeric, at least one letter, and 4 to 8 characters long.
Try this:
(?=.*[a-zA-Z])[a-zA-Z0-9]{4,8}
(?= - we're using a lookahead, so we can check for something without affecting the rest of the match
.*[a-zA-Z] - match for anything followed by a letter, i.e. check we have at least one letter
[a-zA-Z0-9]{4,8} - This will match a letter or a number 4 to 8 times.
However, you say the intention is for "it can't be just all numbers or just all letters", but requirements 1, 2 and 3 don't accomplish this since it's can be all letters and meet all three requirements. It's possible you want this, with an extra lookahead to confirm there's at least one digit:
(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{4,8}
The use of a-zA-Z isn't very international friendly, so you may be better off using an escape code for "letter" if available in your flavour of Regular Expressions.
Also, I hope this isn't matching for acceptable passwords, as 4 characters probably isn't long enough.
number 2 and 3 seem to contradict. The following will match alphanumeric between 4 and 8:
/[0-9a-zA-Z]{4,8}/
?Regex.IsMatch("sdf", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
false
?Regex.IsMatch("sdfd", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
true
?Regex.IsMatch("1234", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
false
Warning on **.* and .+:
// At least one letter does not match with .*
?Regex.IsMatch("1111", "(?=.*[a-zA-Z])[a-zA-Z0-9]{4,8}")
false
?Regex.IsMatch("1aaa", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
true
[a-zA-Z0-9]{4,8}
The first part specifies alphanumeric, and the 2nd part specifies from 4 to 8 characters.
Try: [a-zA-Z0-9]{4,8}

Categories

Resources