Reputation: 121
I'm looking for a regex that will find a dutch phone number inside a piece of text. For example:
Is shouldn't detect
This regex (https://regexr.com/3aevr) seems fine for detecting seperate values:
^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)[1-9]((\s|\s?\-\s?)?[0-9])((\s|\s?-\s?)?[0-9])((\s|\s?-\s?)?[0-9])\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9]$
Unfortunately it does not work for my purposes. Any help is appreciated.
Upvotes: 1
Views: 107
Reputation: 15492
You can try with this regex:
(?<![\d\-])\d{2}-?\d{8}(?!\d)
Explanation:
(?<![\d\-])
: Negative lookbehind that doesn't matches ...
[\d\-]
: a digit or a dash (at the beginning of your number)\d{2}
: two digits-?
: optional dash\d{8}
: eight digits(?!\d)
: Negative lookahead that doesn't matches ...
\d
: a digit (at the end of your number)Try it here.
Note: Lookbehind and lookahead in this regex ensure there are no more than 10 digits in your string (the ones inside the matching pattern).
Upvotes: 1
Reputation: 627119
You can use
(?<![^a-zA-Z\s])((\+|00(\s|\s?-\s?)?)31(\s|\s?-\s?)?(\(0\)[-\s]?)?|0)[1-9]((\s|\s?-\s?)?[0-9])((\s|\s?-\s?)?[0-9])((\s|\s?-\s?)?[0-9])\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9](?![^a-zA-Z\s])
See the regex demo.
The (?<![^a-zA-Z\s])
negative lookbehind makes sure there is an ASCII letter or a whitespace char, or start of string immediately to the left of the current location.
The (?![^a-zA-Z\s])
negative lookahead makes sure there is an ASCII letter or a whitespace char, or end of string immediately to the right of the current location.
Upvotes: 2