Regular Expression notes

Source: Internet
Author: User

Case-insensitive Mode
For a while, when I write regular expressions to match the Drug keyword, I often write expressions like/viagra | CIRA | anti-ed. In order to make it more beautiful, I will sort the keywords; To improve the speed, I will use/[Vv] iagra/instead of/viagra/I, so that only necessary parts can be used in case-insensitive mode. Specifically, I need to perform case-insensitive matching on the first letter of each word.

I wrote a function dedicated to batch conversion.

Copy codeThe Code is as follows:
# Convert regex to sorted list, then provide both lower/upper case for the first letter of each word
# Luf means lower upper first

Sub luf {
# Split the regex with the delimiter |
My @ arr = sort (split (// |/, shift ));

# Provide both the upper and lower case for
# First leffer of each word
Foreach (@ arr) {s/\ B ([a-zA-Z])/[\ l $1 \ u $1]/g ;}

# Join the keyword to a regex again
Join ('|', @ arr );
}

Print luf "sex pill | viagra | CIRA | anti-ed ";
# The output is: [aA] nti-[eE] d | [cC] istrap | [sS] ex [pP] ill | [vV] iagra

Control the next starting position of global match

I remember jyf once asked me how to control the starting position of matching. Well, now I can answer this question. Perl provides the pos function, which can be used to adjust the starting position of the next match in/g Global match. Example:
Copy codeThe Code is as follows:
$ _ = "Abcdefg ";
While (/../g)
{
Print $ &;
}

The output result is every two letters, that is, AB, cd, ef.

You can use pos ($ _) to locate the starting position of the next match, for example:

Copy codeThe Code is as follows:
$ _ = "Abcdefg ";
While (/../g)
{
Pos ($ _) --; # pos ($ _) ++;
Print $ &;
}

Output result:

Copy codeThe Code is as follows:
Pos ($ _) --: AB, bc, cd, de, ef, fg.
Pos ($ _) ++: AB, de.

Read the pos chapter in the Perl document for details.

Hash and regular expression replacement
The third chapter of effective-perl-2e has such an example (see the code below) to escape special symbols.
Copy codeThe Code is as follows:
My % ent = {'&' => 'amp', '<' => 'lt ','> '=> 'gt '};
$ Html = ~ S/([& <>])/& $ ent {$1};/g;

This example is very clever. It flexibly uses the hash data structure, uses the part to be replaced as the key, and uses the corresponding content as the value. In this way, as long as there is a match, the captured part will be captured as the key, and the value will be retrieved and applied to the replacement, reflecting the efficiency of the advanced language.

However, can such Perl code be transplanted to Python? Python also supports regular expressions and hashes (called Dictionary in Python). However, it does not seem to support inserting too many fancy things during the replacement process (replacing the variable in the row with interpolation ).

View the Python documentation (execute python in shell, import re, and help (re )),:

Copy codeThe Code is as follows:
Sub (pattern, repl, string, count = 0)
Return the string obtained by replacing the leftmost
Non-overlapping occurrences of the pattern in string by
Replacement repl. repl can be either a string or a callable;
If a string, backslash escapes in it are processed. If it is
A callable, it's passed the match object and must return
A replacement string to be used.

Like python and php, The callable callback function can be used during the replacement process. The default parameter of this function is a matching object variable. In this way, the problem is simple:

Copy codeThe Code is as follows:
Ent = {'<': "lt ",
'>': "Gt ",
'&': "Amp ",
}

Def rep (mo ):
Return ent [mo. group (1)]

Html = re. sub (r "([& <>])", rep, html)

The key point of the python replacement function callback is that its parameter is a matching object variable. As long as you understand this, check the manual to see what attributes are available for this object and use them one by one to write flexible and efficient python Regular Expression replacement code.

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.