Reputation: 41
So I'm working on a regular expression that can change a specific phone number on a website. I'm slowly getting there, but I cannot figure out how to catch the following numbers: (085)-4017877 (085)4017877.
Also tools like regexr.com tell me the regex catches both numbers here: 085-4017877 But on my current setup it does not catch the first number. Any ideas on why this could be?
Current Regex: \85[-.\s]?4017877\g
The zero at the front of the numbers is ignored on purpose.
What it should catch:
085-4017877 085-4017877 (085)-4017877 (085)4017877 085 4017877 +31854017877
Test: http://regexr.com/39v0b
//step through dom
function recurseDOM(scope, newText, patt)
{
var i = 0, nodes, node;
if(scope.childNodes)
{
nodes = scope.childNodes;
for(i;i<nodes.length;i++)
{
node = nodes[i];
if(node.nodeType === 3)
{
//is a text node
checkTextNode(node, newText, patt);
}
if(node.childNodes)
{
//loop through child nodes if child nodes are found
recurseDOM(node, newText, patt);
}
node = null;
}
nodes = null;
}
}
//Find and replace
function checkTextNode(node, newText, patt)
{
var text = node.data;
var test = patt.test(text);
if(test)
{
//match found, replace node's textual data with specified string
node.data = text.replace(patt, newText);
newText = null;
text = null;
}
test = null;
}
Code Im currently using to replace the number
Upvotes: 2
Views: 181
Reputation: 8389
You're pretty close, this one should catch all your cases:
/85\)?[- ]?4017877/g
It just adds an optional parenthesis before the dash/space character class.
Upvotes: 1
Reputation: 1899
I'd use:
(?:\d{3}\s?|\(\d{3}\)|\+\d{4})-?\d{7}
Breakdown:
(?:
- open non-capture group, for alternate patterns to match (to keep things neat)\d{3}\s?|
- match full area code\(\d{3}\)|
- match area code surrounded by parentheses\+\d{4}
- match country code and area code)
- close non-capture group-?
- hyphen zero or one time\d{7}
- match the last seven digitsNow you can easily change the pattern without headaches by modifying the non-capture group alternates.
Upvotes: -1
Reputation: 251
Your regex is too simple for the patterns you're trying to catch, this regex will match all your test cases:
/(\+31)?(\()?0?85(\)-?| |-)?4017877/
I have made you a test here
Should you want a generic regex for this numbers, need to replace digits with '\d':
/(\+\d\d)?(\()?\d?\d\d(\)-?| |-)?\d\d\d\d\d\d\d/
Upvotes: 1