Regular expression : match either of two conditions? - javascript

Hi I don't know much about regular expression. But I need it in form validation using angularJs.
Below is the requirement
The input box should accept only if either
(1) first 2 letters alpha + 6 numeric
or
(2) 8 numeric
Below are some correct Inputs :-
(1)SH123456
(2)12345678
(3)sd456565
I tried data-ng-pattern="/(^([a-zA-Z]){2}([0-9]){6})|([0-9]*)?$/" , Its working fine for both the above condition but still it is accepting strings like S2D3E4F5 and may be many other combination as well.
What I am doing wrong I am not able to find it out.
Any help is appreciable !!!
Thanks

In your regex, the two alternative branches are anchored separately:
(^([a-zA-Z]){2}([0-9]){6}) - 2 letters and 6 digits at the start of the string
| - or
([0-9]*)?$ - optional zero or more digits at the end of the string
You need to adjust the boundaries of the group:
data-ng-pattern="/^([a-zA-Z]{2}[0-9]{6}|[0-9]{8})?$/"
^ ^^^^
See the regex demo.
Now, the pattern will match:
^ - start of string
( - start of the grouping:
[a-zA-Z]{2}[0-9]{6} - 2 letters and 6 digits
| - or
[0-9]{8} - 8 digits
)? - end of the grouping and ? quantifier makes it match 1 or 0 times (optional)
$ - end of string.

You can try this DEMO LINK HERE
^(([a-zA-Z]{2}|[0-9]{2})[0-9]{6})?$
It will accept:
ab123456
12345678
aa441236
aw222222

Related

How to include dot once as last character in regex?

I'm trying to make regex in JavaScript that matches numbers between 1-100 and includes two decimals.
Example numbers that need to be included in the regex:
1
1.1
1.15
0.5
100
100.00
Example numbers that need to be excluded:
101
100.01
100.1
55.999
This is my regex at the moment:
^(?:100(?:\.00?)?|\d?\d(?:\.\d\d?)?)$
This works otherwise but I also need to include two numbers followed by a decimal or 100 followed by a decimal like this:
14.
9.
100.
This is because I'm running the regex check each time a button is pressed in an input field and even though number like 0.5 is allowed by the current regex, I can't type it in because 0. is not allowed.
You will need to use two separate regexps here, one for the live input validation (just what you described in the question, that will let you input allowed values), and another one for a final "on-submit" validation (that will check the validity of the whole input string).
Otherwise, you won't be able to input 0.5 like values.
The regex for live input validation is:
/^(?:100(?:\.0?0?)?|\d\d?(?:\.\d?\d?)?)$/
See this regex demo. Note how the ? quantifiers make patterns optional, especially the \d and 0 after \. patterns.
The regex for final validation of numbers starting with 0.01 to 100 is
/^(?!0*(?:\.0*)?$)(?:100(?:\.00?)?|\d?\d?(?:\.\d\d?)?)$/
See this regex demo.
Make the numbers after the dot optional, too.
^(?:100(?:\.00?)?|\d?\d(?:\.\d{0,2})?)$
If you want to disallow 0 before the dot if the numbers after are all zero or nothing, probably include a separate negative lookahead for that:
^(?:100(?:\.00?)?|(?!0\.0*$)\d?\d(?:\.\d{0,2})?)$
Nothing here or in your original regex should disallow 0.5; perhaps add more debugging details if that is genuinely something you are grappling with.
You may use this regex for your task:
^(?:0?\.(?:\d?[1-9]|[1-9]\d)|[1-9]\d?(?:\.\d{1,2})?|100(?:\.0{1,2})?)$
RegEx Demo
With your shown samples, could you please try following.
^(?:100(?:\.0{1,2})?|(?:(?:\d\d?)(?:\.\d{1,2})?))$
Online demo for above regex
Explanation: Adding detailed explanation for above.
^ ##Matching from starting of value here.
(?: ##Starting 1st capturing group here.
100(?:\.0{1,2})?| ##matching 100 with or without 1 to 2 zeroes OR
(?: ##Starting 2nd capturing group here.
(?:\d\d?) ##In a non-capturing group matching 0 to 9 and 0 to 9 optional.
(?:\.\d{1,2})? ##In a non-capturing group matching dot followed by 1 or 2 digits
) ##Closing 2nd capturing group here.
)$ ##Closing 1st capturing group at the end of value.

How to write regular expression for this case?

I want to write a regular expression in javascript to match the following valid scenarios. later on, If I have to extract using a group then I will be able to do so.
I have tried the below regex, but it not giving me the desired pattern.
/[0-9][+-[0-9]+]*/
Regex should be able to match the "Valid" scenarios.
// Valid
64344
9434
434-543
434-543
434 - 543
4435 - 343434
1-2,3,5,6
1-2,3,5,6-6,45-4
3,5,6, 8 - 9,24
1-2,3,5 ,6
1- 2,3, 5,6-6,45-4
// Invalid
23 -
2343.3434
343.3434 - 13.466
23 ,
234,
,54
xyz 9
3,5,6,8-9,24,
,35,65,65
,35,65,65 -
,3 5,65,65,
3,5,6, 8- 9,24,
1- 2,3, 5,6-6,4 5-4
, 35,65,6 5
,35, 6 5,65,
Looking at your samples, I feel what you want is a comma separated numbers where some of which can be ranged like 1-2 and also having optional spaces between them and also at start or end of string. Here is a regex you can use,
^\s*\d+(?:\s*-\s*\d+\s*)?(?:\s*,\s*\d+(?:\s*-\s*\d+)?)*\s*$
Explanation:
^ - Start of string
\s* - optional space at start of input
\d+ - Matches one or more just number
(?:\s*-\s*\d+\s*)? - This matches a ranged number like this -2 which can have spaces within it and ? at the end means ranged part is optional
(?:\s*,\s*\d+(?:\s*-\s*\d+)?)* - This regex part ensures that the numbers can be comma separated and \d+(?:\s*-\s*\d+)? part in it enables numbers of 2-3 form where ? in it indicates that it can be just pure number without having ranged part and * whole of this can be zero or more times
\s* - optional space at the end of input
$ - end of input
Live Demo

Conditional regex javascript

I'm trying to make a regex which can match a phone number and so tell me if the phone number is either valid or not.
I would like to verify if there is a country id before the phone number, this one is well formated.
For example : +(33)0123456789 I want to be sure if the user start to type the first parenthesis it must be followed by number and ended by a closing parenthesis.
I have succeeded with PCRE engine
^[+]?((\()?(?(2)[0-9]{1,4})(?(2)\)))?([0-9]{2}){1}([\.\- ]?[0-9]{2}){4}$
But I realized this way doesn't work with javascript engine, conditional is not supported.
^[+]?((\()?((?=\2)[0-9]{1,4})((?=\2)\)))?([0-9]{2}){1}([\.\- ]?[0-9]{2}){4}$
It doesn't fill my needs. I want to check if the first parenthesis is set then it must be followed by number and a closing parenthesis.
So I ask you if there is a workaround in javascript to do this ?
Some help would be really appreciated, thank you :)
The ((\()?(?(2)[0-9]{1,4})(?(2)\)))? part of the regex is matching an optional sequence of smaller patterns. (\()? matches an optional ( and places it in Group 2. Then, (?(2)[0-9]{1,4}) matches 1 to 4 digits if Group 2 matched. Then (?(2)\)) matches ) if Group 2 matched. Basically, this is equal to (?:\([0-9]{1,4})\))?.
Thus, you need no conditional construct here.
You may use
^\+?(?:\([0-9]{1,4})\)?[0-9]{2}(?:[. -]?[0-9]{2}){4}$
See the regex demo
Details
^ - start of string
\+? - an optional +
(?:\([0-9]{1,4})\)? - an optional sequence: (, 1 to 4 digits and )
[0-9]{2} - 2 digits
(?:[. -]?[0-9]{2}){4} - 4 occurrences of an optional space, dot or - followed with 2 digits
$ - end of string.

Possible to make regular expression with sub-query

I am trying to write a regular expression for a bit of javascript code that takes a user's input of a mobile number and in one regular expression, performs the following checks:
Starts with 07
Contains only numbers, whitespace or dashes
Contains exactly 11 numbers
Is this possible to do in just one regular expression and if so, how please?
I don't think it is possible with one regex, but it is possible by testing for two conditions:
if(/^07[\d\- ]+$/.test(str) && str.replace(/[^\d]/g, "").length === 11) {
//string matches conditions
}
Explanation of the regex:
^: Anchor that means "match start of string".
07: Match the string 07. Together with the above, it means that the string must start with 07.
[: Beginning of a character class i.e., a set of characters that we want to allow
\d: Match a digit (equivalent to 0-9).
\-:
" ": Match whitespace (markdown doesn't let me show a single space as code)
]: End of character class.
+: One or more of the previous.
$: Anchor that means "match end of string". Together with the ^, this basically means that this regex must apply to the entire string.
So here we check to see that the string matches the general format (starts with 07 and contains only digits, dashes or spaces) and we also make sure that we have 11 numbers in total inside the string. We do this by getting of anything that is not a digit and then checking to see that the length of the string is equal to 11.
Since #Vivin throws out the challenge :
/^07([-\s]*\d){9}[-\s]*$/
^07 : begin with digits 07
( : start group
[-\s]* : any number of - or whitespace
\d : exactly one digit
){9} : exactly 9 copies of this group (11 digits including 07)
[-\s]* : optional trailing spaces or -
$ : end of string
Of course a more useful way might be as follows
if ((telNo = telNo.replace (/[-\s]+/g, '')).match (/^07\d{9}$/)) {
....
}
which has the advantage (?) of leaving just the digits in telNo
Thank you all for trying, but after a good while trying different ideas, I finally found a working "single" regular expression:
07((?:\s|-)*\d(?:\s|-)*){9}
This make sure that it starts with 07, only contains digits, whitespace or dashes, and only 11 of them (9 plus the first 2) are numbers.
Sorry to have wasted your time.
Explanation:
() - include in capture
(?:) - do not include in capture
\s - whitespace
| - or
- - dash
* - zero or more
\d - digits only
{9} - exactly nine of what is captured

Regular expression for number with length of 4, 5 or 6

I need a regular expression that validate for a number with length 4, 5, 6
I used ^[0-9]{4} to validate for a number of 4, but I do not know how to include validation for 5 and 6.
Try this:
^[0-9]{4,6}$
{4,6} = between 4 and 6 characters, inclusive.
[0-9]{4,6} can be shortened to \d{4,6}
Be aware that, as written, Peter's solution will "accept" 0000. If you want to validate numbers between 1000 and 999999, then that is another problem :-)
^[1-9][0-9]{3,5}$
for example will block inserting 0 at the beginning of the string.
If you want to accept 0 padding, but only up to a lengh of 6, so that 001000 is valid, then it becomes more complex. If we use look-ahead then we can write something like
^(?=[0-9]{4,6}$)0*[1-9][0-9]{3,}$
This first checks if the string is long 4-6 (?=[0-9]{4,6}$), then skips the 0s 0*and search for a non-zero [1-9] followed by at least 3 digits [0-9]{3,}.
If the language you use accepts {}, you can use [0-9]{4,6}.
If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?.
To match standalone 4-6-digit numbers, you may use
^\d{4,6}$ // If full string match is expected
\b\d{4,6}\b // If no letters/digits/underscores are expected on both ends
(?<!\d)\d{4,6}(?!\d) // If no digits are expected on both ends, but letters/_ are allowed
(^|\D)(\d{4,6})(?!\d) // Same as above, in case lookbehinds are not supported (get Group 2 value)
See Regex #1 - Regex #2 - Regex #3 and Regex #4 demos.
Details:
^ - start of string
\b - a word boundary
(?<!\d) - a negative lookbehind that fails the match if there is a digit immediately to the left of the current location
(^|\D) - a capturing group matching either start of string or a non-digit char
\d{4,6} - four, five or six digits
(?!\d) - a negative lookahead that fails the match if there is a digit immediately to the right of the current location
$ - end of string

Categories

Resources