Regular Expression advanced learning skills

Source: Internet
Author: User
Tags alphanumeric characters

What is RE?
Presumably, you have used a-character "*" when searching for files. For example, if you want to find all the Word files in the Windows directory, you may use "*. doc "is used for search, because" * "represents any character. RE is doing something like this, but it is more powerful.

When writing a program, you often need to compare whether the string conforms to a specific style. The main function of RE is to describe this specific style. Therefore, you can regard RE as a descriptive style, for example, "\ w +" represents a non-null string consisting of any letter or number ). The. NET framework provides a very powerful category library to easily use RE for text search and replacement, decoding complex headers, and text verification.
Next, let's try some examples.

Some simple examples
If you want to search for Elvis followed by an alive string in the article, using RE may go through the following process. Parentheses are the meaning of the RE:

1. elvis (search for elvis)

The above indicates that the character order to be searched is elvis. In. NET, the Case sensitivity can be set to slightly different characters. Therefore, "Elvis", "ELVIS", or "eLvIs" are all RESS under 1. But because only the characters appear in the order of elvis, pelvis also conforms to the RESS under 1. You can use the RE of 2 to improve the performance.

2. \ belvis \ B (elvis is regarded as a whole word search, such as when elvis and Elvis are slightly case sensitive)
"\ B" has a special meaning in RE. In the above example, it refers to the word boundary, SO \ belvis \ B defines the front and back boundary of elvis with \ B, that is, the word elvis is required.

Assume that elvis in the same row is followed by an alive string, and the other two special characters "." and "*" are used "*"."." This indicates any character except the line break character, and "*" indicates that the project is repeated * until the RE-compliant string is found. Therefore, ". *" refers to any number of characters except for line breaks. Search for elvis in the same row and find out the alive text string, which can be like 3 RE.

3. \ belvis \ B. * \ balive \ B (FIND THE alive text string followed by elvis, such as elvis is alive)

You can use simple and special characters to form a powerful RE, but it also finds that when more and more special characters are used, RE will become more and more difficult to understand.


Let's look at another example.
Form a valid phone number

If you want to collect 7-digit phone numbers in the format of xxx-xxxx from the web page, where x is a number, RE may write like this.

4. \ B \ d-\ d (find the seven-digit phone number, such as 123-1234)
Each \ d represents a number ." -"Is a general hyphen. To avoid too many repeated \ d, RE can be rewritten as 5.

5. \ B \ d {3}-\ d {4} (search for a better seven-digit phone number, such as 123-1234)
{3} After \ d indicates that the previous project is repeated three times, that is, it is equal to \ d.

RE learning and testing tool Expresso

Because RE is not easy to read and users are prone to errors, Jim has developed a tool software Expresso to help users learn and test the RE. Besides the URL described above, you can also go to the Ultrapico website. After expresso is installed, in expression % 20% 20library, jim builds the example in the article. You can view the article and test it, or try to modify the re under the example, I can see the result immediately, and the younger brother thinks it is very useful. You can try it. /". After Expresso is installed, in Expression Library, Jim builds many examples of the article. You can view the article and test it, or try to modify the RE under the example, I can see the result immediately, and the younger brother thinks it is very useful. You can try it.

Basic concepts of RE in. NET
Special characters

Some characters have special meanings, such as "\ B", ".", "*", and "\ d ." \ S represents any space character, such as spaces, tabs, and newlines .." \ W represents any letter or number.

Let's look at some examples.
6. \ ba \ w * \ B (search for words starting with a, such as able)
This RE description is used to find the start boundary of a word (\ B), followed by the letter "a", plus any number of letters and numbers (\ w *), then terminate the end boundary of the word (\ B ).

7. \ d + (search for numeric strings)
"+" And "*" are very similar, except that + must repeat the previous project at least once. That is to say, there must be at least one number.

8. \ B \ w {6} \ B (search for six letters and numbers, such as ab123c)

The following table lists the special characters commonly used by RE.

. Any character except for line breaks
\ W any letter or Digit
\ S any space character
\ D any number character
\ B defines the word boundary
^ The beginning of The article, for example, "^ The'' indicates that The string that appears at The beginning of The article is ""
$ End of an article, such as "End $", indicates that the End of an article appears as "End"
Special characters "^" and "$" are used to search for certain words that must be the beginning or end of an article. They are especially used to verify whether the input meets a certain style, for example, if you want to verify a seven-digit phone number, you may enter the following 9 RE.

9. ^ \ d {3}-\ d {4} $ (verify the phone number with seven digits)

This is the same as the 5th RE, but there are no other characters before and after it, that is, the entire string only has the seven numbers of phone numbers. In. if the Multiline option is set in. NET, "^" and "$" compare each line, as long as the beginning and end of a line meet the RE, instead of the entire article string for a comparison.

Conversion character (Escaped characters)

Sometimes, you may need literal meaning instead of special characters, in this case, the "\" character is used to remove special characters, so "\ ^ ","\. "," \ "represents" ^ ",". the literal meaning.

Repeat the preceding project

I have read "{3}" and "*" before to repeat the preceding characters. Then we will see how to repeat the entire description (subexpressions) with the same syntax ). The following table describes how to repeat the preceding items.

* Repeat any number of times
+ Repeat at least once
? Zero or one repetition
{N} repeated n times
{N, m} repeats at least n times, but does not exceed m times
{N ,}repeat at least n times

Let's try some examples.

10. \ B \ w {5, 6} \ B (search for five or six alphanumeric characters, such as as25d and d58sdf)
11. \ B \ d {3} \ s \ d {3}-\ d {4} (find the phone number of ten numbers, such as 800 123-1234)
12. \ d {3}-\ d {2}-\ d {4} (find a social insurance number, such as 123-45-6789)
13. ^ \ w * (the first word in each line or entire article)
In Espresso, try the difference between Multiline and no Multiline.

Match characters in a certain range

How to identify specific characters? In this case, brackets "[]" come in handy. Therefore, [aeiou] looks for the vowels "a", "e", "I", "o", and "u", [.?!] What are you looking ".","?" ,"!" These symbols remove the special meanings of special characters in brackets, that is, they are interpreted as literal meanings. You can also specify characters in a certain range, such as "[a-z0-9]", referring to any lowercase letter or any number.

Next, let's look at a complicated RE-Example for finding phone numbers.

14 .\(? \ D {3} [(] \ s? \ D {3} [-] \ d {4} (find the phone number of 10 digits, for example (080) 333-1234)

Such a RE can be used to find phone numbers in multiple formats, such as (080) 123-4567, 511 254 6654, and so on ." \(?" Represents one or zero left parentheses (", and" [(] "indicates finding a right parentheses") "or space character," \ s ?" It refers to one or zero space character groups. However, such a RE will find a phone number like "800) 45-3321", that is, there is no symmetric balance between the brackets, and you will learn to choose one later (alternatives) to solve this problem.

Not included in a specific character group (Negation)

Sometimes you need to find the characters contained in a specific character group. The following table describes how to perform such a description.

\ W is not an arbitrary character of letters and numbers
\ S is not any character of the space character
\ D is not an arbitrary number character
\ B is not at the word boundary
[^ X] Not any character of x
[^ Aeiou] is not any character of a, e, I, o, u

15. \ S + (a string that does not contain space characters)

Alternatives)

Sometimes you need to find several specific options. At this time, the special character "|" comes in handy. For example, search for the zip code of five and nine numbers (.

16. \ B \ d {5}-\ d {4} \ B | \ B \ d {5} \ B (search for five numbers and nine numbers ("-")) zip code)

When using Alternatives, you need to pay attention to the order before and after, because in Alternatives, RE will first select the project that matches the leftmost, and in 16, if you put the item that finds the five numbers in front, the RE will only find the zip code of five digits. If you have learned how to choose one, you can make a better correction of 14.

17. (\ d {3} \) | \ d {3}) \ s? \ D {3} [-] \ d {4} (10-digit phone number)

Grouping)

Parentheses can be used to describe a description. Through the description, you can repeat or process the description.

18. (\ d {1, 3} \.) {3} \ d {1, 3} (find a simple RE of the network address)

This RE indicates the first part (\ d {1, 3 }\.) {3} refers to a number with a minimum of three digits followed ". symbol. There are three numbers in this type, followed by one to three digits, that is, numbers such as 192.72.28.1.

However, this may lead to a disadvantage because the network address number can only reach 255 at most, but the above RE is consistent as long as it is one to three digits, therefore, we need to make the comparison number smaller than 256, but only using RE alone cannot make such comparison. In 19, use the option to limit the address to the required range, that is, 0 to 255.

19. (2 [0-4] \ d | 25 [0-5] | [01]? \ D ?) \.) {3} (2 [0-4] \ d | 25 [0-5] | [01]? \ D ?) (Search for network addresses)

Have you noticed that RE is getting more and more like what aliens say? Simply look for the network address, directly look at the RE are full of difficult to understand miles.

Expresso Analyzer View

Expresso provides a function that converts the next RE into a tree description. A group of separate descriptions provide a good debugging environment. Other functions, such as partially conforming (Partial Match only searches for the part of the anti-white RE) and Exclude Match (Exclude Match only does not look for the part of the anti-white RE) are left for you to try.

When the sub-description is grouped in parentheses, the text that matches the sub-description can be used in subsequent program processing or RE itself. Under the predefined condition type, the corresponding group is named by a number, starting from 1, and from left to right. This automatic group is named, you can see it in skeleton view or result view in Expresso.

Backreference is used to find the same text captured in a group. For example, "\ 1" refers to the text captured by Group 1.

20. \ B (\ w +) \ B \ s * \ 1 \ B (looking for repeated words, the repetition here refers to the same word, there is a blank space in the middle to separate words such as dog)
(\ W +) captures at least one character of the letter or number, and name it group 1, and then search for any space character, followed by the same text as Group 1.

If you do not like the automatic group name 1, you can also name it yourself. In the preceding example, (\ w +) is rewritten (? <Word> \ w +). This is to name the captured group as Word, and the Backreference must be rewritten to \ k. <Word>
21. \ B (? <Word> \ w +) \ B \ s * \ k <Word> \ B (use a self-naming group to capture duplicate words)

There are many special syntax elements using parentheses. The more common list is as follows:

Captures)
(Exp) Match exp and capture it into the automatically named group
(? <Name> exp) matches the exp and crawls it into the named group name.
(? : Exp) conforms to exp and does not capture it.
Lookarounds
(? = Exp) text that matches the word ending with exp
(? <= Exp) text prefixed with exp
(?! Exp) match the text that is not followed by the exp character.
(? <! Exp) text that is not prefixed with exp
Comment
(? # Comment) Annotation

Positive Lookaround

Next we will talk about lookahead and lookbehind assertions. They are currently looking for text that matches the previous text or text that does not contain the current text. These are just like the special characters "^" and "\ B". They do not correspond to any text (used to define the position), and therefore are called zero-width assertions, some examples may be clear.

(? = Exp) is a "zero-width positive lookahead assertion ". It refers to the text that matches the word ending with exp, but does not contain exp itself.

22. \ B \ w + (? = Ing \ B) (the end of the word is ing. For example, filling matches fill)
(? <= Exp) is a "zero-width positive lookbehind assertion ". It refers to the text with the prefix exp, but does not contain the exp itself.

23 .(? <= \ Bre) \ w + \ B (for example, repeated matches peated)
24 .(? <= \ D) \ d {3} \ B (three digits at the end of the word, followed by a digit)
25 .(? <= \ S) \ w + (? = \ S) (a string of letters and numbers separated by space characters)

Negative Lookaround

As mentioned earlier, how to find a character that is not specific or not in a specific group. But what if we only want to verify that a character does not exist and do not match these characters in? For example, if you want to find a word with q in its letter, but the next letter is not u, you can use the following RE for it.

26. \ B \ w * q [^ u] \ w * \ B (a word with q in its letter, but the following letter is not u)

This RE has a problem, because [^ u] corresponds to a character, so if q is the last letter of the word, [^ u] in this way, the space character is matched, and the result may conform to two characters, such as Iraq haha. You can solve this problem by using Negative Lookaround.

27. \ B \ w * q (?! U) \ w * \ B (a word with q in its letter, but the following letter is not u)
This is "zero-width negative lookahead assertion ".

28. \ d {3 }(?! \ D) (three digits are not followed by one digit)

Similarly, you can use (? <! Exp), "zero-width negative lookbehind assertion", to match the text string that is not prefixed with exp.

29 .(? <! [A-z]) \ w {7} (a string of seven letters and numbers without letters or spaces)

30 .(? <= <(\ W +)> .*(? = <\// \ 1> (text in the HTML volume compartment)
This uses lookahead and lookbehind assertion to retrieve the text between HTML, excluding the HTML Tag.

Comments Please)
Another special purpose of parentheses is to wrap comments. The syntax is "(? # Comment) ". If the" Ignore Pattern Whitespace "option is set, the space character in the RE will be slightly used when the RE is used. When this option is set, the text after "#" will be omitted.

31. Add comments to the text in the HTML volume compartment

(? <= # Search for a prefix, but does not contain it
<(\ W +)> # HTML Tag
) # End search prefix
. * # Match any text
(? = # Search for the end of a word, but it is not included
<\/\ 1> # The string that matches the captured group 1, that is, the HTML tag of the parentheses
) # End searching

Find the most character and the least character (Greedy and Lazy)
When RE is used to find the repetition of a range (for example, ". *"), it usually looks for the highest number of characters, that is, Greedy matching. For example.

32. a. * B (the most character that starts to end with a and ends with B)

If a string is "aabab", the matching string obtained by the preceding RE is "aabab", because this is the word with the most characters. Sometimes it is expected to match the minimum character, that is, lazy matching. Add the question mark (?) You can change all of them to lazy matching. So "*?" This indicates the number of repeated attempts, but the minimum number of repeated attempts is used. For example:

33. .*? B (the minimum character that starts to end with a and ends with B)

If a string is "aabab", the first matching string obtained by the preceding RE is "aab" and then "AB", because this is the word with the least characters.

*? Repeat any number of times. The minimum number of repeat is the principle.
+? Repeat at least once. The minimum number of repeat is the principle.
?? Zero or one repetition. The minimum repetition count is the principle.
{N, m }? Repeat at least n times, but not more than m times.
{N ,}? Repeat at least n times.

Nothing to mention?

So far, many RE-creation elements have been mentioned. Of course, many elements have not been mentioned. The following table lists some unmentioned elements, the number in the leftmost field is an example in Expresso.

# Syntax description

\ A Bell character
\ B Usually refers to the word boundary. In a character group, it represents backspace.
\ T Tab

34 \ r Carriage return

\ V Vertical Tab
\ F From feed

35 \ n New line
\ E Escape

36 \ nnn ASCII octal code: nnn character

37 \ xnn characters with a 16-digit nn

38 \ unnnn Unicode: nnnn character

39 \ cN Control N characters, for example, Ctrl-M is \ cM

40 \ A string start (similar to ^, but does not require the multiline option)

The end of the 41 \ Z string
\ Z string end

42 \ G start of current search

For example, \ p {Lowercase_Letter} refers to the character of the Unicode character group named name.
(?> Exp) Greedy description, also called non-backtracking description. This only works once and does not support backtracking.

44 (? <X>-<y> exp)

Or (? -<Y> exp) balance the group. Complex but easy to use. It allows the named capture group to be used in the stack. (The younger brother doesn't know this too well)

45 (? Im-nsx: exp) Change RE option for the next description exp, such (? -I: Elvis) is to turn off the Elvis case-sensitive option.

46 (? Im-nsx.
(? (Exp) yes | no) exp is regarded as zero-width positive lookahead. If yes, yes is described as the next conformity. If no, no is described as the next conformity.
(? (Exp) yes) Same as the above but no description
(? (Name) yes | no) if the name group is the name of a valid group, yes is described as the next conformity. If no, no is described as the next conformity.

47 (? (Name) yes) Same as the above but no description

Related Article

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.