I have a list of phone numbers which are formatted in multiple ways such as: (212)-555-1234 or 212-555-1234 or 2125551234.
Using JavaScript, what would be the best way to extract only the area code out of these strings?
First, remove everything that is not a digit to get the plain number. Then, get the first three digits via slicing:
return myString.replace(/\D/g,'').substr(0, 3);
Get the first 3 consecutive digits...
/[0-9]{3}/.exec("(212)-555-1234")[0]
Sample (fiddle):
console.log(/[0-9]{3}/.exec("(212)-555-1234")[0]); // 212
console.log(/[0-9]{3}/.exec("212-555-1234")[0]); // 212
console.log(/[0-9]{3}/.exec("2125551234")[0]); // 212
Take the first 3 digits of a 10 digit number, or the first 3 digits after the 1 of an 11 digit number starting with 1. This assumes your domain is U.S. phone numbers.
You can also use my library.
https://github.com/Gilshallem/phoneparser
Example
parsePhone("12025550104");
result: { countryCode:1, areaCode:202, number:5550104, countryISOCode:"US" }
Regex as '^\(*(\d{3})' should do it. Get the first group from the match.
Here ^ will start the match from beginning, \d{3} will match 3 digits. \(* will match the optional starting parenthesis. You don't need to care about next digit or symbols after the area code.
Related
Am trying to validate a mobile number 254777123456 against a regex /^((254|255)[0-9]+){9,15}$/, the mobile number should be prefixed with the country codes specified but the total length of the mobile number should not be more than 15 characters, doing this via javascript am getting null, can anyone point out what am doing wrong.
PS. Am using way more country codes than the ones I specified, I just put those two as a test before I add the others because they will all be separated by the pipe.
Your regex ^((254|255)[0-9]+){9,15}$ means, that pick at least 4 digits (of which first 3 should be either 254 or 255) and whole of them must occur at least 9 times to max 15 times, which will mean the minimum length of string that will match should be of 36 characters. Which obviously you don't want. Your regex needs little correction where you need to take [0-9] part out and have {9,12} quantifier separately. Correct regex to be used should be this,
^(?:(?:254|255)[0-9]{9,12})$
This regex will match 254 or 255 separately and will restrict remaining number to match from 9 to 12 (as you want max number to be matched of length 15 where 3 numbers we have already separated out)
Demo
var nums = ['254777123456','255777123456','255777123456123','2557771234561231']
for (n of nums) {
console.log(n + " --> " + /^(?:(?:254|255)[0-9]{9,12})$/g.test(n));
}
I have one regexp which is finding only 2 digit numbers. I'm trying with \#break:[0-9][0-9]\s\minutes this regexp. It has only 2 digits. How I can rewrite this to detect any number even it 5 or 6 digits.
/\d+/ should do the trick.
"d" is the symbol for digits and "+" tells it to accept one or more.
Try it with d+ as Kevin said: \#break:\d+\s\minute
Or if you exactly know how many digits should be found, just use \#break:\d{1,5}\s\minute, which will catch digits from 1 to 5.
I want regex which finds out continues max 12 digits long number by ignoring space, plus (+), parenthesis & dash, e.g:
Primary contact number +91 98333332343 call me on this
My number is +91-983 333 32343
2nd number +1 (983) 333 32343, call me
Another one 983-333-32343
One more +91(983)-333-32343 that's all
121 street pin code 421 728 & number is 9833636363
Currently, I have a regex, which does the job of fetching contact numbers from string:
/* This only work for the first case not for any other
and for last one it outputs "121" */
\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+
So what can be done here to support all the above cases, in short ignoring special characters and length should range from 10-12.
I see that there are numbers ranging from 10 to 13 digits.
You may use
/(?:[-+() ]*\d){10,13}/g
See the regex demo.
Details:
(?:[-+() ]*\d){10,13} - match 10 to 13 sequences of:
[-+() ]* - zero or more characters that are either -, +, (, ), or a space
\d - a digit
var re = /(?:[-+() ]*\d){10,13}/gm;
var str = 'Primary contact number +91 98333332343 call me on this\nMy number is +91-983 333 32343\n2nd number +1 (983) 333 32343, call me\nAnother one 983-333-32343\nOne more +91(983)-333-32343 that\'s all\n121 street pin code 421 728 & number is 9833636363';
var res = str.match(re).map(function(s){return s.trim();});
console.log(res);
The accepted answer will match your criteria but I'd like to propose a more restrictive approach. It is quite specific to the number formats you provided :
test specifically if a string IS a number /^(\+(\d{1,2})[- ]?)?(\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4,5}$/
test whether a string contains at least one number : /(\+(\d{1,2})[- ]?)?(\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4,5}/
I made you a small fiddle where you can try out different regexes on any number of... well numbers : https://jsfiddle.net/u51xrcox/5/.
have fun.
so I'm making this regular expression to verify some text boxes on a website that I'm designing for an internship.
The problem is that I'm not so keen on regular expressions, and I'm close to having a working one that matches a number between 0-24 and no more than two decimal places.
This is what I have so far. The pattern is also matching any string; such as, "a" or "az".
var pattern = "^([0-9]{0,2}?.?[0-9]{0,2}|1[0-9].?[0-9]{0,2}|2[0-4].?[0-9]{0,2})$";
To get a number between 0 and 24 (24 excluded) with optional up to two decimal places:
^(\d|1\d|2[0-3])(\.\d{1,2})?$
The decimal part:
\. - match the decimal dot
\d{1,2} - one or two digits
()? - makes it optional
The whole part:
\d - numbers 0-9
1\d - numbers 10-19
2[0-3] - numbers 20-23
(x|y|z) - one of x, y or z
As for the "why is my version matching things like "a" and "az" part" - it's a little complex, but it basically boils down to you using dots (like .?). In regex, a dot means "any one character". To make it match a literal dot, you need to escape it with a slash just like I did.
Minor remark: If you want optional leading zero for single digit numbers, replace 1\d with [01]\d. If you want mandatory leading zero for single digit numbers, replace \d|1\d with [01]\d. If you don't want leading zeroes, leave it as it is.
Assuming you do not want 05 or 5.50
^((?:[0-9]|1[0-9]|2[0-3])(?:\.(?:[1-9]|[0-9][1-9]))?)$
You can try it here
The following is a quick attempt to match a floating point number from 0 to 24.99 with up to two non-zero digits
^(([0-9])|([01][0-9])|(2[0-4]))(\.[0-9]{1,2})?$
I think it might be easier to use math to do this though...
You can see the explanation of the entire regex as well as test it out here. I have also added a few test cases.
^(\d|[01]\d|2[0-3])(\.\d{1,2})?$
Test cases:
Valid:
22
1.29
2.99
9.99
13.24
17.38
20.01
02.15
15.35
23.56
1.1
Invalid:
24.29
235.215
21.256
To get a integer number between 1 and 23: ^([1-9]|1[0-9]|2[0-3])$
I have a string E.g 1001, which needs to be exactly 4 chars and can be any combination of 0 and 1, but not all zeros (all ones is ok).
I thought of:
^[01]{4}$
won't work because it accepts 0000
I will be using PHP or JavaScript to do this.
Just adding a detail.
I will be using this to validate the answers for a multi choise questionnaire before they go in the database therefore the string will have length N depending on the number of choices for the question.
so a function to provide the general solution would be great.
It should work
^(?!0000)[01]{4}$
DEMO
Note: Use gm as modifier
Read more about Lookahead and Lookbehind Zero-Length Assertions that actually matches characters, but then gives up the match, returning only the result: match or no match.
Pattern explanation:
^ the beginning of the string
(?! look ahead to see if there is not:
0000 '0000'
) end of look-ahead
[01]{4} any character of: '0', '1' (4 times)
$ end of the string
Another simple solution is this:
^[01]{4}(?<=100|10|1)$
Based on your two possible values [0,1] you only have 8 distinct possibilities:
0000
0001
0010
0011
0100
0101
0110
0111
1111
Your original Regex would hit on all these values. However, the positive look-behind code ensures that the code will either end in '1, '10' or '100'. This covers all possible values except 0000.
The regex:
^(1[01]{3}|01[01]{2}|001[01]|0001)$
Will work and does not rely on look-ahead or look-behind operations which are not, necessarily, available in all regex implementations. Although, now that the question has been edited to provide the languages which will be used: Both PHP and JavaScript regular expressions have negated look-ahead. In those languages, the regex ^(?!0000)[01]{4}$ will work.
The regex at the top of this answer uses multiple terms to build up successively more explicit matches as each character position is specified. The point is that there must be at least one 1 character in the matching four character string. Once a 1 character is encountered in the string, we do not care what the remaining characters are, other than being [01].
The first term 1[01]{3} will match any four 0 and 1 digits that start with 1. This covers all desired matching strings where the first digit is a 1 leaving only desired strings starting with 0 not yet defined as matching.
The second term 01[01]{2} will match any four 0 and 1 digits that start with 01. This leaves only desired strings which start with 00 not yet defined as matching.
The third term 001[01]{2} will match 0010 and 0011
The fourth term 0001 matches the one desired string not matched by the other terms.
Validate an N character long non-zero binary string:
Use a regex comparison and a length check:
Your comments indicate that you have much longer (e.g. 40 characters) similar strings which you need to match in other circumstances.
Given that you have the need to check various different length strings, you are probably best off creating a single function which is able to test multiple different lengths.
In JavaScript, a possibility would be:
function isNonZeroBinaryStringOfLengthN(str, len) {
//True if string is all 0 or 1 with at least one 1 and is the right length.
return (str.length == len && /^[01]*1[01]*$/.test(str) );
}
It is not a good idea to only use the built in functions to parse the string to an integer:
For this circumstance, you are probably best off sticking with a regex based solution rather than using either the PHP intval($str,2) or JavaScript parseInt(str,2). The reason for this is that neither function properly validates the string.
In PHP the command:
echo intval('011134011',2);
prints
7
In JavaScript the command:
console.log(parseInt("0101382730101",2));
prints:
5
This means that if you use one of the internal string->int parsing functions, you still have to separately validate the string you are passing to either function to match ^[01]{n}$. Given that you must to that anyway, you are probably better off using the single regex and length test mentioned above without parsing the string to an int.