Regex limit the number of letters total in the entire string - javascript

I have this expression which is almost what I need:
/(?=^.{5,12}$)(^[a-zA-Z\u0590-\u05fe]{0,4}[0-9]{3,8}[a-zA-Z\u0590-\u05fe]{0,4}$)/
except, I need to only allow 4 letters total (4 in the beginning and 0 in the end,3 and 1, 2 and 2, 0 and 4, etc...)
allowed inputs:
11abcd11
1abcdefg123
abcd1234
unallowed inputs:
1abcd11
abcd123
1abcd12
is there a way to achieve this? thanks!

To make sure there are exactly four letters in the string, you can use
^(?=.{5,12}$)(?=(?:[^a-zA-Z\u0590-\u05fe]*[a-zA-Z\u0590-\u05fe]){4}[^a-zA-Z\u0590-\u05fe]*$)[a-zA-Z\u0590-\u05fe]{0,4}[0-9]{3,8}[a-zA-Z\u0590-\u05fe]{0,4}$
See the regex demo
The (?=(?:[^a-zA-Z\u0590-\u05fe]*[a-zA-Z\u0590-\u05fe]){4}[^a-zA-Z\u0590-\u05fe]*$) positive lookahead makes sure there are four sequences of any zero or more "non-letters" followed with a "letter" and then there are zero or more "non-letters" till the end of string.
If you can target ECMAScript 2018+ compliant engines you can use a Unicode-aware version:
/^(?=.{5,12}$)(?=(?:\P{L}*\p{L}){4}\P{L}*$)\p{L}{0,4}[0-9]{3,8}\p{L}{0,4}$/u
See this regex demo, where \p{L} matches letters. You may also replace it with \p{Alphabetic} which also matches letters that are Roman numbers.

Related

Regex validating string of numbers

I am trying create regex witch will start with some number like 230, 420, 7456. Then could be some number in interval 1-9 but the final length must be 9.
For example 230888333 or 745623777
I create this:
([(230|420|7456)[0-9]{1,}]{9})
But it is not correct. Any idea how to make this correct?
Thaks.
The pattern that you tried is not anchored, and the current notation uses a character class [...] instead of a grouping (the ]{9} part at the end repeats 9 times a ] char)
If you use C# then use [0-9] to match a digit 0-9.
You can either assert 9 digits in total:
^(?=[0-9]{9}$)(?:230|420|7456)[0-9]+$
Regex demo
Or write an alternation for different leading lengths of digits:
^(?:(?:230|420)[0-9]{6}|7456[0-9]{5})$
Regex demo
You can simply add a check for length first and then simple regex
function checkString(str){
return str.length === 9 && /^(?:230|420|7456)\d+$/.test(str)
}
console.log(checkString("230888333"))
console.log(checkString("745623777"))
console.log(checkString("123"))
console.log(checkString("230888333123"))

javascript regex : possible to have a range in the quantifier? [duplicate]

I've written a regular expression that matches any number of letters with any number of single spaces between the letters. I would like that regular expression to also enforce a minimum and maximum number of characters, but I'm not sure how to do that (or if it's possible).
My regular expression is:
[A-Za-z](\s?[A-Za-z])+
I realized it was only matching two sets of letters surrounding a single space, so I modified it slightly to fix that. The original question is still the same though.
Is there a way to enforce a minimum of three characters and a maximum of 30?
Yes
Just like + means one or more you can use {3,30} to match between 3 and 30
For example [a-z]{3,30} matches between 3 and 30 lowercase alphabet letters
From the documentation of the Pattern class
X{n,m} X, at least n but not more than m times
In your case, matching 3-30 letters followed by spaces could be accomplished with:
([a-zA-Z]\s){3,30}
If you require trailing whitespace, if you don't you can use: (2-29 times letter+space, then letter)
([a-zA-Z]\s){2,29}[a-zA-Z]
If you'd like whitespaces to count as characters you need to divide that number by 2 to get
([a-zA-Z]\s){1,14}[a-zA-Z]
You can add \s? to that last one if the trailing whitespace is optional. These were all tested on RegexPlanet
If you'd like the entire string altogether to be between 3 and 30 characters you can use lookaheads adding (?=^.{3,30}$) at the beginning of the RegExp and removing the other size limitations
All that said, in all honestly I'd probably just test the String's .length property. It's more readable.
This is what you are looking for
^[a-zA-Z](\s?[a-zA-Z]){2,29}$
^ is the start of string
$ is the end of string
(\s?[a-zA-Z]){2,29} would match (\s?[a-zA-Z]) 2 to 29 times..
Actually Benjamin's answer will lead to the complete solution to the OP's question.
Using lookaheads it is possible to restrict the total number of characters AND restrict the match to a set combination of letters and (optional) single spaces.
The regex that solves the entire problem would become
(?=^.{3,30}$)^([A-Za-z][\s]?)+$
This will match AAA, A A and also fail to match AA A since there are two consecutive spaces.
I tested this at http://regexpal.com/ and it does the trick.
You should use
[a-zA-Z ]{20}
[For allowed characters]{for limiting of the number of characters}

Javascript regex for extracting certain part of string

I need to extract certain part of Javascript string. I was thinking to do it with regex, but couldn't come up with one which does it correctly.
String can have variable length & can contain all possible characters in all possible combinations.
What I need to extract from it, is 10 adjacent characters, that match one of next two possible combinations:
9 numbers & 1 letter "X" (capital letter "X", not X as variable letter!)
10 numbers
So, if input string is this: "[1X,!?X22;87654321X9]ddee", it should return only "87654321X9".
I hope I've explained it good enough. Thanks in advance!
This Regex will work:
\d{9}X|\d{8}X\d|\d{7}X\d{2}|\d{6}X\d{3}|\d{5}X\d{4}|\d{4}X\d{5}|\d{3}X\d{6}|\d{2}X\d{7}|\d{1}X\d{8}|\d{10}|X\d{9}
As described, It need to match 9 digits and any letter, and the letter can be at any position of the sequence.
\d{9}X # will match 9 digits and a letter in the end
\d{8}X\d # will match 8 digits a lettter then a digit again
...
\d{1}X\d{8} # will match 1 digits a lettter then 8 digits
\{10} # will match 10 digits
Edited to match only X
You can use this much simpler regex:
/(?!\d*X\d*X)[\dX]{10}/
RegEx Breakup:
(?!\d*X\d*X) # negative lookahead to fail the match if there are 2 X ahead
[\dX]{10} # match a digit or X 10 times
Since more than one X is not allowed due to use of negative lookahead, this regex will only allow either 10 digits or ekse 9 digits and a single X.
RegEx Demo
This regex has few advantages over the other answer:
Much simpler regex that is easier to read and maintain
Takes less than half steps to complete which can be substantial difference on larger text.

Regex to match only when expression match is no more than 12 characters long

I am trying to create a regular expression (Java/JavaScript) that matches the following regex, but only when there are fewer than 13 characters total (and a minimum of 4).
(COT|MED)[ABCD]?-?[0-9]{1,4}(([JK]+[0-9]*)|(\ DDD)?) ← originally posted
(COT|MED)[ABCD]?-?[0-9]{1,4}(([JK]+[0-9]*)|(\ [A-Z]+)?)
These values should (and do) match:
MED-123
COTA-1224
MED4
COTB-892K777
MED-33 DDD
MED-234J5678
This value matches, but I don't want it to (I want to only match if there are fewer than 12 characters total):
COT-1111J11111111111111
See http://regexr.com/3bs7b http://regexr.com/3bsfv
I have tried grouping my expression and putting {4,12} at the end, but that just makes it look for 4 to 12 instances of the whole expression matching.
I feel like I am missing something simple...thanks in advance for your help!
You can use negative look-ahead:
(?!.{13,})(COT|MED)[ABCD]?-?[0-9]{1,4}(([JK]+[0-9]*)|(\ DDD)?)
Since your expression already make sure that a match starts with COT or MED and there is at least one digit after that, it already guarantees that there are at least 4 characters
I have tried grouping my expression and putting {4,12} at the end, but
that just makes it look for 4 to 12 instances of the whole expression
matching.
This looks for 4 to 12 instances of the whole expression because you didn't add a word boundary \b. Your regex works fine, just add a word boundary and your desired outcome would be achieved. Take a look at this DEMO.
Your regex seems to be very clumsy and looks a little bit hard to read. It is also very limited to certain characters example JK except if you want it to be that way. For a more general pattern, you can check this out
(COT|MED)[AB]?-?[\dJK]{1,8}(\s+D{1,3})?\b
(COT|MED): matches either COT or MED
[AB]?: matches A or B which is optional because of the presence of ?
-?: matches - which is also optional
[\dJK]{1,8}: This matches a number,or J or K with a length of at least one character and a maximum of eight characters.
(\s+D{1,3})?: matches a space or a D at least one time and a maximum of 3 times and this is optional
\b: with respect to your question this seems to be the most important and it creates a boundary for the words that have already been matched. This means that anything exceeding the matched pattern would not be captured.
See the demo here DEMO2
The answer you are looking for is
(?!\S{13})(?:COT|MED)[ABCD]?-?\d{1,4}(?:[JK]+\d*|(?: [A-Z]+)?)
See regex demo
Note that it is almost impossible to check the length of a phrase that is not a whole string or that has spaces inside since boundaries are a bit "blurred". Thus, (?!\S{13}) is a kind of a workaround that just makes sure you do not have a string without whitespace that is 13 characters long or longer.
The regex breakdown:
(?!\S{13}) - Check if the substring that follows does not consist of 13 non-whitespace characters
(?:COT|MED) - Any of the values in the alternation (COTorMED`)
[ABCD]?-? - Optional A, B, C, D and then an optional -
\d{1,4} - 1 to 4 digits
(?:[JK]+\d*|(?: [A-Z]+)?) - a group of 2 alternatives:
[JK]+\d* - J or K, 1 or more times, and then 0 or more digits
(?: [A-Z]+)? - optional space and 1 or more Latin uppercase letters
As this answer suggests, you could solve this this way:
(?=(COT|MED)[ABCD]?-?[0-9]{1,4}(([JK]+[0-9]*)|(\ DDD)?))(?={4 , 12})

Regular Expression. 20 Alphabetical letters and up to 2 of ( . - _ )

I'm trying to build up a regex pattern for the html input field which only allows up to 20 combined alphabetical letters and digits which can only have up to two of Dashes(-), Underscores(_) and fullstops (.)
So something like only two of the symbols allowed and any amount of letters and digits allowed, combined they've got to be between 4 and 20.
What would the pattern for this be?
An sample (non functioning) version could be like [A-Za-z0-9([\._-]{0,2})]{4,20}
Solution:
I decided to go with #pascalhein #Honore Doktorr answer which is to use a lookahead.
The final pattern is ^(?=[A-Za-z0-9]*([._-][A-Za-z0-9]*){0,2}$)[A-Za-z0-9._-]{4,20}$
You can verify the length with a lookahead at the beginning:
^(?=.{4,20}$)
Then list all the cases that are allowed for your regex separately:
[A-Za-z0-9]* (no special chars)
[A-Za-z0-9]*[._-][A-Za-z0-9]* (one special char)
[A-Za-z0-9]*[._-][A-Za-z0-9]*[._-][A-Za-z0-9]* (two special chars)
It isn't beautiful, but I believe it should work. This is the final expression:
^(?=.{4,20}$)([A-Za-z0-9]*|[A-Za-z0-9]*[._-][A-Za-z0-9]*|[A-Za-z0-9]*[._-][A-Za-z0-9]*[._-][A-Za-z0-9]*)$
Edit:
Actually, it might be nicer to test the number of special characters with a lookahead instead:
^(?=[A-Za-z0-9]*([._-][A-Za-z0-9]*){0,2}$)[A-Za-z0-9._-]{4,20}$
I encourage you to not to use a Regex when there are functions for the porpuse you want to achieve.
An advice I give to jrs on this topic is to use a regex for single porpuses, if there is more than one porpuse, use more regex.
to answer your question:
1 your valid characters from start to end.
var 1stregex = /^[A-Za-z0-9._-]{4,20}$/;
2 Count must be 0 to 2, which in javascript is .match().length.
var 2ndregex = /([._-])/;
if(myText.match(1stregex) && myText.match(2ndregex).length <=2)
{ isvalid=true; }

Categories