Skip to content
Advertisement

Grep Regex: How to find multiple area codes in phone number?

I have a file: each line consist of a name, room number, house address, phone number.

I want to search for the lines that have the area codes of either 404 or 202. I did “(404)|(202)” but it also gives me lines that had the numbers in the phone number in general instead of from area code, example:

JavaScript

I do not want the above, I am targeting lines like this, examples:

JavaScript

Advertisement

Answer

Let’s consider this test file:

JavaScript

The distinguishing feature of area codes, as opposed to other three digit numbers, is that they have a space before them and a - after them. Thus, use:

JavaScript

More complex example

Suppose that phone numbers appear at the end of lines but can have any of the three forms 808-543-2029, 8085432029, or 808 543 2029 as in the following example:

JavaScript

To select the lines with 202 or 404 area codes:

JavaScript

If it is possible that the phone numbers are followed by stray whitespaces, then use:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement