Regexp to allow letters, numbers and - - javascript

I have a problem with creating regexp to allow:
exactly 2 letters at the beginning
exactly 10 numbers after letters
at most 4 "-" between numbers (should allow also without it)
so example of valid string is GB123-55-22-22-6,
my current regexp is: /^([A-Z]{2})?[0-9]{10}$/. He allow GB1235522226 but I have a problem with "-".
can somoene tell me how to allow this regexp to use at most 4 "-" chars?
thanks for any help!

You can use
^(?:[A-Z]{2})?(?=(?:-?\d){10}$)[0-9]+(?:-[0-9]+){0,4}$
See the regex demo.
Details:
^ - start of string
(?:[A-Z]{2})? - optional two letters
(?=(?:-?\d){10}$) - there must be 10 digits optionally separated with a - till end of string, the string must end with a digit
[0-9]+ - one or more digits
(?:-[0-9]+){0,4} - zero to four occurrences of a hyphen and then one or more digits
$ - end of string.

Related

How do I enforce that certain characters must be present when there is an optional character before them?

I would like to capture a string that meets the criteria:
may be empty
if it is not empty it must have up to three digits (-> \d{1,3})
may be optionally followed by a uppercase letter ([A-Z]?)
may be optionally followed by a forward slash (i.e. /) (-> \/?); if it is followed by a forward slash it must have from one to three digits
(-> \d{1,3})
Here's a valid input:
35
35A
35A/44
Here's invalid input:
34/ (note the lack of a digit after '/')
I've come up with the following ^\d{0,3}[A-Z]{0,1}/?[1,3]?$ that satisfies conditions 1-3. How do I deal with 4 condition? My Regex fails at two occassions:
fails to match when there is a digit and a forward slash and a digit e.g .77A/7
matches but it shouldn't when there isa digit and a forward slash, e.g. 77/
You may use
/^(?:\d{1,3}[A-Z]?(?:\/\d{1,3})?)?$/
See the regex demo
Details
^ - start of string
(?:\d{1,3}[A-Z]?(?:\/\d{1,3})?)? - an optional non-capturing group:
\d{1,3} - one to three digits
[A-Z]? - an optional uppercase ASCII letter
(?:\/\d{1,3})? - an optional non-capturing group:
\/ - a / char
\d{1,3} - 1 to 3 digits
$ - end of string.
Visual graph (generated here):
This should work. You were matching an optional slash and then an optional digit from 1 to 3; this matches an optional combination of a slash and 1-3 of any digits. Also, your original regex could match 0 digits at the beginning; I believe that this was in error, so I fixed that.
var regex = /^(\d{1,3}[A-Z]{0,1}(\/\d{1,3})?)?$/g;
console.log("77A/7 - "+!!("77A/7").match(regex));
console.log("77/ - "+!!("77/").match(regex));
console.log("35 - "+!!("35").match(regex));
console.log("35A - "+!!("35A").match(regex));
console.log("35A/44 - "+!!("35A/44").match(regex));
console.log("35/44 - "+!!("35/44").match(regex));
console.log("34/ - "+!!("34/").match(regex));
console.log("A/3 - "+!!("A/3").match(regex));
console.log("[No string] - "+!!("").match(regex));

Regex validation for mixed digits for a max of 6 characters

I need a regex validation for mixed length, a total length of 6 characters in that 4-6 characters in caps/numbers and 0-2 spaces.
I tried like
^[A-Z0-9]{4,6}+[\s]{0,2}$
but it results in a max length of 8 characters, but I need a max of 6 characters.
If the alphanumeric chars should only appear at the start of the string and the whitespaces can appear at the end (i.e. the order of the alphanumerics and whitespaces matters), you may use
/^(?=.{6}$)[A-Z0-9]{4,6}\s*$/
See the regex demo
Details
^ - start of string
(?=.{6}$) - the string length is restricted to exactly 6 non-line break chars
[A-Z0-9]{4,6} - 4, 5 or 6 uppercase ASCII letters or digits
\s* - 0+ whitespaces (but actually, only 0, 1 or 2 will be possible to add as the total length is already validated with the lookahead)
$ - end of string.
If you want to match the alphanumeric and whitespaces anywhere inside the string, you need a lookaround based regex like
^(?=(?:[^A-Z0-9]*[A-Z0-9]){4,6}[^A-Z0-9]*$)(?=(?:\S*\s){0,2}\S*$)[A-Z0-9\s]{6}$
See the regex demo
Details
^ - start of string
(?=(?:[^A-Z0-9]*[A-Z0-9]){4,6}[^A-Z0-9]*$) - a positive lookahead that requires the presence of 4 to 6 letters or digits anywhere inside the string
(?=(?:\S*\s){0,2}\S*$) - a positive lookahead that requires the presence of 0 to 2 whitespaces anywhere inside the string
[A-Z0-9\s]{6} - 6 ASCII uppercase letters, digits or whitespaces
$ - end of string.
To shorten the pattern, the second lookahead can be written as (?!(?:\S*\s){3}), it will fail the match if there are 3 whitespace chars anywhere inside the string. See the regex demo.
You can use | characters to accommodate several cases into one.
const regex = /(^[A-Z0-9]{4}\s{2}$)|(^[A-Z0-9]{5}\s$)|(^[A-Z0-9]{6}$)/g;
alert(regex.test(prompt('Enter input, including space(s)')));
If you want to match zero, one or two spaces at the end, you could use an alternation for those 3 cases.
^(?:[A-Z0-9]{4}[ ]{2}|[A-Z0-9]{5}[ ]|[A-Z0-9]{6})$
Regex demo
Explanation
^ Assert the start of the string
(?: Non capturing group
[A-Z0-9]{4}[ ]{2} Match uppercase or digit 4 times followed by 2 spaces
| Or
[A-Z0-9]{5} Match uppercase or digit 5 times followed by 1 space
| Or
[A-Z0-9]{6} Match uppercase or digit 6 times
) Close non capturing group
$ Assert the end of the string

RegExp - How to check for both parentheses in the string

I'd like to know how can I match text ONLY if there are both parentheses (starting and closing).
Currently, my RegExp is: ^1?\s?\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}$.
It checks for US valid numbers, however \(? and \)? makes the difference. It should match the text if there is 0 of them or 2.
Some tests:
1 555)555-5555 - false
555)-555-5555 - false
(555-555-5555 - false
Now, they all return the same result - true.
Here is the link to it:
https://regexr.com/3kjei (^ is because I have to select only one string without any line break, please remove 2 other strings from it so you can see it returns true. All of the strings in this link should return true, just check it so only one string is in the text editor).
Thank you
You may use
^(?:1\s?)?(?:\(\d{3}\)|\d{3})[-\s]?\d{3}[-\s]?\d{4}$
See the regex demo.
Note that ^1?\s? in your regex allow a single whitespace in the beginning, that is why I suggest ^(?:1\s?)? - an optional sequence starting with 1 that is optionally followed wih whitespace.
The \(?\d{3}\)? part is replaced with (?:\(\d{3}\)|\d{3}) - a non-capturing group that matches either (+3 digits+) or 3 digits (so, no (123 or 123)` can be matched).
Details
^ - start of string
(?:1\s?)? - 1 or 0 occurrences of 1 optionally followed with 1 whitespace char
(?:\(\d{3}\)|\d{3}) - either (, 3 digits, ) or just 3 digits
[-\s]? - an optional - or whitespace
\d{3} - 3 digits
[-\s]?- an optional - or whitespace
\d{4} - 4 digits
$ - end of string.
Why not in the portion of your regex that says \(?\d{3}\)? that you "or" it instead.
Eg. Replace it with something like this:
((\(\d{3}\))|\d{3})

Hyphen and Underscore should never be continuous but can be present in the string more than once

I have a requirement, where i have to validate a field in Excel.
Validations:
Field should start and end with [a-zA-Z0-9] but not with any special chars [-_]
It cannot contain "-" and "_" continuously more than once.
Example:
A--Badasd (Not allowed)
A__Bsdasdas (Not allowed)
A-_fdsfdsd (Not Allowed)
A_-sfsdfsdf (Not allowed)
A-B-adf (allowed)
A_b_adads (allowed)
I came up with this following regex, however, it doesn't seem to accept even the non-continuous entries of "-" and "_".
^[a-zA-z0-9]+(([\xFF01-\xFF5E]+|[\\-\\_])+)[a-zA-Z0-9]+$
[\xFF01-\xFF5E] is to not allow any double width characters, so please ignore it as it is working fine.
Any help would be greatly appreciable.
I can only suggest a lookahead based pattern (as [\xFF01-\xFF5E] matches _ and restricting it in JS regex will make the pattern more cumbersome):
/^[a-z0-9](?:(?!.*?[-_]{2})[\xFF01-\xFF5E-]*[a-z0-9])?$/i
See the regex demo.
This pattern will match strings of 1 char length, too, and will only match those strings starting and ending with an ASCII alphanumeric char and not having --, _-, -_ and __ in them.
If you want to "block" strings of length 1, i.e. set the minimum match length to 2, you should remove (?: and )? from the pattern above:
/^[a-z0-9](?!.*?[-_]{2})[\xFF01-\xFF5E-]*[a-z0-9]$/i
Details
^ - start of string
[a-z0-9] - an alphanumeric ASCII char
(?:(?!.*?[-_]{2})[\xFF01-\xFF5E_-]*[a-z0-9])? - an optional (1 or 0 occurrences) sequence of:
(?!.*?[-_]{2}) - a lookahead check that will fail the match if there are 2 consecutive - or _ anywhere after any 0+ chars other than line break chars
[\xFF01-\xFF5E-]* - any char in the \xFF01-\xFF5E range or/and -
[a-z0-9] - an alphanumeric ASCII char
$ - end of string.

How to match digit in middle of a string efficiently in javascript?

I have strings like
XXX-1234
XXXX-1234
XX - 4321
ABCDE - 4321
AB -5677
So there will be letters at the beginning. then there will be hyphen. and then 4 digits. Number of letters may vary but number of digits are same = 4
Now I need to match the first 2 positions from the digits. So I tried a long process.
temp_digit=mystring;
temp_digit=temp_digit.replace(/ /g,'');
temp_digit=temp_digit.split("-");
if(temp_digit[1].substring(0,2)=='12') {}
Now is there any process using regex / pattern matching so that I can do it in an efficient way. Something like string.match(regexp) I'm dumb in regex patterns. How can I find the first two digits from 4 digits from above strings ? Also it would be great it the solution can match digits without hyphens like XXX 1234 But this is optional.
Try a regular expression that finds at least one letter [a-zA-Z]+, followed by some space if necessary \s*, followed by a hyphen -, followed by some more space if necessary \s*. It then matches the first two digits \d{2} after the pattern.:
[a-zA-Z]+\s*-\s*(\d{2})
may vary but number of digits are same = 4
Now I need to match the first 2 positions from the digits.
Also it would be great it the solution can match digits without hyphens like XXX 1234 But this is optional.
Do you really need to check it starts with letters? How about matching ANY 4 digit number, and capturing only the first 2 digits?
Regex
/\b(\d{2})\d{2}\b/
Matches:
\b a word boundary
(\d{2}) 2 digits, captured in group 1, and assigned to match[1].
\d{2} 2 more digits (not captured).
\b a word boundary
Code
var regex = /\b(\d{2})\d{2}\b/;
var str = 'ABCDE 4321';
var result = str.match(regex)[1];
document.body.innerText += result;
If there are always 4 digits at the end, you can simply slice it:
str.trim().slice(-4,-2);
here's a jsfiddle with the example strings:
https://jsfiddle.net/mckinleymedia/6suffmmm/

Categories