Regex - match range of characters with a quantifier that only matches numbers - javascript

I've found a similar question on SO, but nothing I can get my head around. Here's what I need;
6 or more digits, with these characters allowed \s\-\(\)\+
So here's what I have /^[0-9\s\-\(\)\+]{6,}$/
The problem is, I don't want anything other than the number to count towards the 6 or more quantifier. How can I only "count" the digits? It would also been good if I could stop those other allowed characters from being entered adjacently e.g:
0898--234
+43 34 434
After an hour of reading up and looking at a regex cheat sheet, I'm hoping some kind person can point me in the right direction!

You could do something like this:
/^([\s()+-]*[0-9]){6,}[\s()+-]*$/
This will match any number of special characters (whitespace, parentheses, pluses or hyphens) followed by a single decimal digit, repeated 6 or more times, followed by any number of special characters.
Or this if you don't want to match two or more adjacent special characters:
/^([\s()+-]?[0-9]){6,}[\s()+-]?$/

You can use lookahead:
/^(?=(\D*\d){6,})[0-9\s()+-]{6,}$/

/^[\s()+-]*(\d[\s()+-]*){6,}$/
This doesn't count the 'cruft'. It allows any number of special characters, followed by six times [a digit followed by any number of special characters].
If you want max. one special character in between digits, use ? instead of *, but I assume you don't care much for more than one special character at the start or at the end, so I'd go with
/^[\s()+-]*(\d[\s()+-]?){6,}[\s()+-]*$/
This matches any number of special characters, followed by 6 or more times [a digit followed by at most one special character], followed by any number of special characters.
Another option would be to strip your special characters from the string first, and then match against 6 or more digits.
var rawInput = " 12 (3) -- 4 -5 ++6";
var strippedInput = rawInput.replace(/[\s()+-]*/g, "");
return new RegExp("^\d{6,}$").test(strippedInput);
Remember that you have a complete programming language at your disposal. I've noticed people tend to decide they need to use regex and then forget about everything else they can do.

Related

What is this regex: /^\D(?=\w{5})(?=\d{2})/ is not matching "bana12"? [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
The objective is to match strings that are greater than 5 characters long, do not begin with numbers, and have two consecutive digits. I thought my regex was enough to do that but is not matching "bana12".
This regex does the job:
var pwRegex = /^\D(?=\w{5})(?=\w*\d{2})/;
Is not this regex more restrictive than mine? Why do I have to specify that the two or more digits are preceded by zero or more characters?
It is less restrictive than yours.
After the \D, there are 2 lookaheads. For your regex, they are
(?=\w{5})(?=\d{2})
This means that the thing after the non-digit must satisfy both of them. That is,
there must be 5 word characters immediately after the non-digit, and
there must be 2 digits immediately after the non-digit.
There is ana12 immediately after the non digit in the string. an is not 2 digits, so your regex does not match.
The working regex however has these two lookaheads:
(?=\w{5})(?=\w*\d{2})
It asserts that there must be these two things immediately after the \D:
5 word characters, and
a bunch of word characters, followed by two digits
ana12 fits both of those descriptions.
Try this Regex101 Demo. Look at step 6 in the regex debugger. That is when it tries to match the second lookahead.
You were on the right track to maybe use lookaheads, and also with the correct start of your pattern, but it is missing a few things. Consider this version:
^\D(?=.*\d{2})\w{4,}$
Here is an explanation of the pattern:
^ from the start of the string
\D match any non digit character
(?=.*\d{2}) then lookahead and assert that two consecutive digits occur
\w{4,} finally match four or more word characters (total of 5 or more characters)
$ end of the string
The major piece missing from your current attempt is that it only matches one non digit character in the beginning. You need to provide a pattern which can match 5 or more characters.

Javascript regex: check if a string is alphanumeric AND it contains a letter (at least)

The string length can be 4 - 12 characters.
It may contain ONLY letters and numbers, but it has to contain at least 1 number.
And I need to solve this with a single regex pattern.
I tried something like:
/^(?=.*[a-z]*)(?=.*[0-9]+).{4,12}$/i
This won't accept less than 4 or more than 12 chars and it also checks if the string contains a number, but obviously it's not good because of the .* parts.
I wasn't able to figure out how to exclude all non-alphanumeric characters.
Any help would be appreciated!
Thanks in advance!
I think your pattern is close, but I would use this:
/^(?=.*[0-9])[a-z0-9]{4,12}$/i
The only lookahead you need is one which asserts that there is a single number. There is no requirement for there to be any letters, so don't bother adding an assertion for that. Then, match any alphanumeric character 4 to 12 times.
console.log(/^(?=.*[0-9])[a-z0-9]{4,12}$/i.test('abc'));
console.log(/^(?=.*[0-9])[a-z0-9]{4,12}$/i.test('123'));
console.log(/^(?=.*[0-9])[a-z0-9]{4,12}$/i.test('abcd'));
console.log(/^(?=.*[0-9])[a-z0-9]{4,12}$/i.test('Abc1'));

Regex which accepts alphanumerics only, except for one hyphen in the middle

I am trying to construct a regular expression which accepts alphanumerics only ([a-zA-Z0-9]), except for a single hyphen (-) in the middle of the string, with a minimum of 9 characters and a maximum of 20 characters.
I have verified the following expression, which accepts a hyphen in the middle.
/^[a-zA-Z0-9]+\-?[a-zA-Z0-9]+$/
How can I set the minimum 9 and maximum 20 characters for the above regex? I have already used quantifiers + and ? in the above expression.
How would I apply {9,20} to the above expression? Are there any other suggestions for the expression?
/^[a-zA-Z0-9]+\-?[a-zA-Z0-9]+$/
can be simplified to
/^[a-z0-9]+(?:-[a-z0-9]+)?$/i
since if there is no dash then you don't need to look for more letters after it, and you can use the i flag to match case-insensitively and avoid having to reiterate both lower-case and upper-case letters.
Then split your problem into two cases:
9-20 alpha numerics
10-21 characters, all of which are alpha numerics except one dash
You can check the second using a positive lookahead like
/^(?=.{10,21}$)/i
to check the number of characters without consuming them.
Combining these together gives you
/^(?:[a-z0-9]{9,20}|(?=.{10,21}$)[a-z0-9]+-[a-z0-9]+)$/i
You can do this provided you don't want - to be present exactly in middle
/^(?=[^-]+-?[^-]+$)[a-zA-Z\d-]{9,20}$/
[^-] matches any character that is not -

Javascript - Matching a hyphen in regex

I'm trying to match a string using regex (of which I am new to) but I can't get it to match.
These should be accepted:
GT-00-TRE
KK-10-HUH
JU-05-OPR
These should not:
HTH-00-AS
HM-99-ASD
NM-05-AK
So the pattern goes 2 letters, hyphen, 2 digits (between 00 and 11 inclusive), hyphen, 3 letters.
So far the best I can come up with is:
var thePattern = /^[a-z]{2}[-][00-11][-][a-z]{3}$/gi;
I can't help but feel that I'm pretty close.
Can anyone give me any pointers?
Thanks.
This should be what you need:
var thePattern = /^[a-z]{2}[-](0\d|1[0-1])[-][a-z]{3}$/gi;
In order to do a range 00-11, you have to say "(0 followed by 0-9) or (1 followed by 0 or 1)". This is because specifying a range within [] only works for single digits. Luckily your case is pretty simple, otherwise it could get quite complex to work around that.
Your regex is OK, but for one thing: the digits matching is a bit more complex
(0\d|10|11)
you want to match a zero followed by a digit (\d) OR (|) a ten OR a eleven.
Something in square brackets represents just a single character in a range. [0-5] means any single digit between 0 and 5, [a-q] means any lowercase letter from a to q. There's no such thing as [00-11] because it would require to work on more than one character at a time.

Regular Expression with optional elements in input string in javascript

Can anyone give me the regular expression for currency which have the following formats :
1000 - valid
1,000 - valid
1,000.00 or 1000.00 - valid.
This means, the number May or May Not contain a comma(,) separator every 3 digits.
The number May Or May Not contain a dot (.), and if it carries a dot(.) it should show atleast 1 number after the decimal place.
And lastly it should be numerical characters only. If I need to make my question clear kindly suggest.
/^\d{1,3}(?:(?:,\d{3})*|(?:\d{3})*)(?:\.\d{1,2})?$/
"Between one and three digits, then any number of groups of three digits prefixed by a comma or any number of groups of three digits not prefixed by said comma (disallowing a mix of the two kinds of groups), then an optional group of one or two digits prefixed by a dot."
Note: This regex assumes that you want to validate an entire string against the criteria outlined in your question. If you want to use it to find such numbers in a longer string, you will need to remove the ^ and $ from the beginning and end of the expression.
Something like so should work: (,?\d{3})+(\.\d{2})?. The regex will attempt to match a sequence of 3 digits precedeed by an optional comma, which is then, finally followed by an optional decimal point and 2 digits.
Please refer to this tutorial for more information.
EDIT: As per the comment below, the above regex can fail. I would recommend first using this regular expression: ^[\d][\d.,]+$ to make sure that you only have digits, thousand and decimal seperators. This regular expression will also make sure that the number starts with a digit, not with anything else. You could most likely have one regular expression which does everything, but it will most likely be quite complex.

Categories

Resources