Ryan
Ryan

Reputation: 1164

Regex - Get number that is 10 or 11 digits long only

So, I've written a Regex equation to fetch UK phone numbers, it looks like this:

[(]*\d{3}[)]*\s*[.\-\s]*\d{3}[.\-\s]*\d{4}

It captures phone numbers perfectly, however if I provide a list which includes a number longer than 11 digits etc: 01234567891011121314, it will fetch the first 11 digits of that number.

I want to exclude this number altogether, rather than fetching the first 11 digits.

How can I do modify my expression to make this happen?

Thanks

EDIT: For context: The regex is used to fetch phone numbers from website source code, so the numbers can be surrounded by any character at all, I just want to capture those that don't have numbers surrounding them (making them over 11 digits)

EDIT 2: Here's some source code for perspective:

<a class="social" href="https://www.facebook.com/pages/x-Ltd/194636607281565" target="_blank" title="Like us on facebook">
    <i class="icon icon-facebook"></i>
</a>
<p>123 Sesame Street</p>
<p>Brooklyn, NY</p>
<p>Contact Us: 0123 456 7890</p>

The phone number will not always have a < following it.

Upvotes: 1

Views: 1013

Answers (1)

Cameron Roe
Cameron Roe

Reputation: 290

You can utilize anchoring on the regular expression to make sure whatever is being matched only matches if it is exact, size and all. Adding a ^ to the start of the regular expression will indicate the regular expression must start at the start of the string and adding a $ to the end of the regular expression will indicate the the regular expression must end at the end of the string.

So, try this:

^[(]*\d{3}[)]*\s*[.\-\s]*\d{3}[.\-\s]*\d{4}$

Upvotes: 3

Related Questions