Reputation: 555
I'm trying to extract phone number from a string which can be empty or look like one of the following examples:
In addition, a phone number could look like this: (0039) 234786 So the constant(s) are "Tél. :" and/or "Port. :"
The have put these numbers in two variables (cell & landline).
I've tried split and indexOf functions but I'm pretty sure that there's a better and more efficient way to do this.
Any ideas ?
Upvotes: 3
Views: 4244
Reputation: 2168
Here's a regular expression that looks for both versions of your phone number.
The two patterns are separated by a pipe character (|).
On the left side of the pipe, it looks for digit digit space four times in a row, then a final digit digit.
On the right side of the pipe, it looks for parenthesis, then four digits in a row, then end parenthesis, then a space, then six digits in a row.
I tested it in regexr.com by copying and pasting your text and then in the top field, entering this:
/(((\d{2})(\s)){4}(\d){2})|(\((\d){4}\)(\s)(\d){6})/g
Note: regexr.com supplies outer slashes, so no need to include that from the above example, and defaults to a global "g" flag at the end.
Upvotes: 1
Reputation: 2265
If you already know your string is a phone number, just replace all non-numeric characters to leave your phone number:
telInteger = parseInt(inputString.replace(/[^0-9]/g,''));
That way, it doesn't matter what the format is, you always get the number.
If you don't know your string has a phone number, and you're just searching in the wild, you can use the RegEx's in the other answers to detect a phone number.
Hope this helps
Upvotes: 4
Reputation: 463
Using RegEx:
((Tél.\s:\s)(?([\d\s]+))?\s?([\d]+)?)?((Port.\s:\s)([\d\s]+))?
This should capture everything that you are trying to get.
I saw you said you don't have much experience with RegEx...me neither, but I just went through this tutorial (http://regexone.com/) this morning and I feel pretty confident using them now. It's really not that much to learn (at least to be able to do a whole lot with)!
Just so you know, I did check this with a RegEx tool and it worked!
Upvotes: 0