Regular expression phone number (one) (1000)

Foreword

I have compiled 1,000 regular expressions to facilitate communication together.

text

If we want to match a phone number, for example:
707-827-7019

How should we match it?

First, we determine that we enter: 707-827-7019

Then it can certainly be matched.

Next: We found only numbers and-characters.

Then [0-9] {3}-[0-9] {3}-[0-9] {4}

Match like above.

It became [0-9] {3}. [0-9] {3}. [0-9] {4}

Recall that [0-9] means \ d, \ d means a number.

-In fact, it is a non-number, so you can use / D to represent non-numbers.

It became like this: \ d {3} \ D \ d {3} \ D \ d {4}

Then found that / d {3} and / d {3} are duplicated, which definitely has optimization means.

^ (\ d {3} [.-]?) {2} \ d {4} $ This solves the duplication. I replaced \ D with [.-] here because it is more precise. [.-]?> \ d> .. Similarly, I added ^ and $ in front and back, which respectively represent what starts with,

And end with what, add restrictions.

Similarly, the above is considered with the area code, but we still have to consider the following two types:

(707)827-7019
827-7019

Some people write phone numbers, not area codes, or they say the area codes are in parentheses.
Then be compatible.

^(\(\d{3}\)|^\d{3}[.-]?)?\d{3}[.-]?\d{4}

to sum up

The rule is a process of loosening first, then tightening, and then loosening.
Match it first, then add a condition to one example, and finally match more examples, and then relax the condition.

Guess you like

Origin www.cnblogs.com/aoximin/p/12741023.html