Teach you how to use regular expressions in half an hour

Source: Internet
Author: User
Tags ereg
Many may have headaches for regular expressions. today, I have added some articles to my understanding and hope to use expressions that can be understood by ordinary people. share your learning experience with you. starting with The regular expression, you must talk about ^ and $. they are used to match The start and end of a string respectively. The following are examples of ^ The: must start with The string; ofdespair $: The regular expression at The end.

Many people may have a headache with regular expressions. today, I want to share my learning experience with you through my understanding and online articles.

The beginning is still worth mentioning ^ and $ are used to match the start and end of the string respectively. The following are examples:

"^ The": must start with "The" string; "of despair $": must end with a "of despair" string;

So,

"^ Abc $": a string that must start with abc and end with abc. In fact, only abc matches

"Notice": match a string containing notice

You can see that if you didn't use the two characters we mentioned (the last example), that is, the pattern (regular expression) can appear anywhere in the string to be tested, and you didn't lock it to either side.

Next, let's talk about '*', ', and '? ',

They are used to indicate the number or sequence of occurrences of a character. they represent:

"Zero or more" is equivalent to {0,}, "one or more" is equivalent to {1,}, "zero or one." is equivalent to {0, 1}. Here are some examples:

"AB *": it is synonymous with AB {0,}. it matches a string starting with a and followed by 0 or N B ("a", "AB ", "abbb", etc)

; "AB": it is synonymous with AB {1,}. it is the same as the above, but at least one B must exist ("AB", "abbb", etc .);

"AB? ": It is synonymous with AB {0, 1} and can have no or only one B;

"? B $ ": match one or more strings ending with B plus 0 a. key points, '*','', and '? 'Only the character before it.

You can also limit the number of characters in braces, such

"AB {2}": requires that a be followed by two B (one cannot be less) ("abb"); "AB {2 ,}": requires that a be followed by two or more B (such as "abb", "abbbb", etc .); "AB {3, 5}": requires 2-5 B ("abbb", "abbbb", or "abbbbb") after ").

Now we can put a few characters in parentheses, for example:

"A (bc) *": Match a with 0 or a "bc"; "a (bc) {}": one to five "bc ."

There is also a character '│', which is equivalent to the OR operation:

"Hi │ hello": match string containing "hi" or "hello;

"(B │ cd) ef": matches strings containing "bef" or "cdef;

"(A │ B) * c": matches strings containing multiple (including 0) a or B, followed by a string of c;

A point ('.') can represent all single characters, excluding "\ n"

What if we want to match all single characters including "\ n?

By the way, use the '[\ n.]' mode.

"A. [0-9]": add a character to an a and a number ranging from 0 to 9.

"^. {3} $": end of any three characters.

The content enclosed in brackets only matches a single character.

"[AB]": Match a or B (same as "a │ B );

"[A-d]": match a single character from 'A' to 'D' (same effect as "a │ B │ c │ d" and "[abcd ); generally, we use [a-zA-Z] to specify a character as a case-sensitive English character.

"^ [A-zA-Z]": matches strings starting with an uppercase/lowercase letter.

"[0-9] %": match a string containing x %

", [A-zA-Z0-9] $": match a string ending with a comma plus a number or a letter

You can also include characters you don't want in brackets, you only need to use '^' in the brackets to start with "% [^ a-zA-Z] %" to match a non-letter string containing two percentage signs.

Key point: ^ when used at the beginning of the brackets, it indicates that the characters in the brackets are excluded.

To be able to explain in PHP, you must add ''in front of these characters and escape some characters.

Do not forget that the character in the brackets is an exception to this rule-in the brackets, all the special characters, including (''), all will lose their special nature "[*\? {}.] "Match strings containing these characters.

Also, as the regx manual tells us: "If the list contains ']', it is best to use it as the first character in the list (possibly following '^ ). if it contains '-', it is better to put it at the beginning or the end, or a range of the second end point [a-d-0-9] in the middle of '-' will be valid.

After reading the example above, you should have understood {n, m. note that n and m cannot be negative integers, and n is always less than m. in this way, you can match at least n times and at most m times. for example, "p {}" matches the first five p in "pvpppp ".

Which of the following statements start \?

\ B indicates that it is used to match a word boundary, that is,... for example, 've \ B '. it can match the ve in love but not in very.

\ B is the opposite of \ B above.

Well, let's make an application:

How to build a pattern to match the number of currency input

Construct a matching pattern to check whether the input information is a number that represents money. We think there are four ways to indicate the number of money:

"10000.00" and "10,000.00", or no decimal part, "10000" and "10,000". now let's start building this matching mode:

^ [1-9] [0-9] * $

This variable must start with a number other than 0, but it also means that a single "0" cannot pass the test. The following is a solution:

^ (0 │ [1-9] [0-9] *) $

"Only numbers starting with 0 and not 0 match", we can also allow a negative number before the number:

^ (0 │ -? [1-9] [0-9] *) $

This is: "0 or a number that starts with 0 and may have a negative number in front. "Well, now let's not be so rigorous. we can start with 0. now let's give up the negative number, because we don't need to use it to represent coins. we now specify a pattern to match the fractional part:

^ [0-9] (\. [0-9])? $

This implies that the matched string must start with at least one Arabic number. but note that in the above mode, "10. "It does not match. only" 10 "and" 10.2 "are allowed. (Do you know why)

^ [0-9] (\. [0-9] {2 })? $

We have specified two decimal places. if you think this is too harsh, you can change it:

^ [0-9] (\. [0-9] {1, 2 })? $

This will allow one or two decimal places. Now we add a comma (every three digits) to increase readability, which can be expressed as follows:

^ [0-9] {1, 3} (, [0-9] {3}) * (\. [0-9] {1, 2 })? $

Do not forget that ''can be replaced by '*'. if you want to allow blank strings to be input (why ?). Do not forget that the backslice bar '\' may cause errors in the php string (common errors ).

Now we can confirm the string. now we can remove all the commas (,) from str_replace (",", "", $ money) then we can regard the type as double and then use it for mathematical computation.

Next:

Construct a regular expression for checking email

There are three parts in a complete email address:

1. username (everything on the left ),

2 .'@',

3. server name (that is, the remaining part ).

The user name can contain uppercase and lowercase letters, Arabic numerals, periods ('. '), minus sign ('-'), and underline ('_'). the server name also complies with this rule, except for the underlines.

The start and end of the user name cannot be a period. the same is true for servers. you cannot have at least one character between two consecutive periods. now let's take a look at how to write a matching pattern for the user name:

^ [_ A-zA-Z0-9-] $

The end cannot exist yet. we can add the following:

^ [_ A-zA-Z0-9-] (\. [_ a-zA-Z0-9-]) * $

The above means: "At least one canonicalized character (except.) starts with 0 or more strings starting with a vertex ."

To simplify it, we can use eregi () to replace ereg (). eregi () is case-insensitive and we don't need to specify two ranges: "a-z" and "A-Z"-just specify one:

^ [_ A-z0-9-] (\. [_ a-z0-9-]) * $

The server name is the same, but the underline should be removed:

^ [A-z0-9-] (\. [a-z0-9-]) * $

Okay. now you only need to use @ to connect the two parts:

^ [_ A-z0-9-] (\. [_ a-z0-9-]) * @ [a-z0-9-] (\. [a-z0-9-]) * $

This is the complete email authentication matching mode. you only need to call

Eregi ('^ [_ a-z0-9-] (\. [_ a-z0-9-]) * @ [a-z0-9-] (\. [a-z0-9-]) * $', $ eamil)

Then you can check whether the email is used.

Other regular expressions

Extract string

Ereg () and eregi () has a feature that allows users to extract a part of a string through regular expressions. for example, we want to extract a file name from path/URL-the following code is what you need:

Ereg ("([^ \/] *) $", $ pathOrUrl, $ regs );

Echo $ regs [1];

Advanced replacement

Ereg_replace () and eregi_replace () are also very useful: if we want to replace all the negative signs at intervals with commas:

Ereg_replace ("[\ n \ r \ t]", trim ($ str ));

Finally, I will check the regular expression of the EMAIL for you to analyze the article.

"^ [-! # $ % & \ '* \./0-9 =? A-Z ^ _ 'a-z {|} ~] '.'@'.'[-! # $ % & \ '* \/0-9 =? A-Z ^ _ 'a-z {|} ~] \.'.'[-! # $ % & \ '* \./0-9 =? A-Z ^ _ 'a-z {|} ~] $"

If it is easy to understand, the purpose of this article has been achieved.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.