![]() |
|
Without the \Q, the regex would also spuriously match "di". What is
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
While this actually can be done, it's much harder than you'd think. For example, this one-liner
|
will work in many but not all cases. You see, it's too simple-minded for certain kinds of C programs, in particular, those with what appear to be comments in quoted strings. For that, you'd need something like this, created by Jeffrey Friedl and later modified by Fred Curtis.
|
This could, of course, be more legibly written with the /x modifier, adding
whitespace and comments. Here it is expanded, courtesy of Fred Curtis.
|
A slight modification also removes C++ comments:
|
Historically, Perl regular expressions were not capable of matching balanced text. As of more recent versions of perl including 5.6.1 experimental features have been added that make it possible to do this. Look at the documentation for the (??{ }) construct in recent perlre manual pages to see an example of matching balanced parentheses. Be sure to take special notice of the warnings present in the manual before making use of this feature.
CPAN contains many modules that can be useful for matching text depending on the context. Damian Conway provides some useful patterns in Regexp::Common. The module Text::Balanced provides a general solution to this problem.
One of the common applications of balanced text matching is working with XML and HTML. There are many modules available that support these needs. Two examples are HTML::Parser and XML::Parser. There are many others.
An elaborate subroutine (for 7-bit ASCII only) to pull out balanced and possibly nested
single chars, like ` and ', { and }, or (
and ) can be found in http://www.cpan.org/authors/id/TOMC/scripts/pull_quotes.gz .
The C::Scan module from CPAN also contains such subs for internal use, but they are undocumented.
Most people mean that greedy regexes match as much as they can. Technically speaking, it's
actually the quantifiers (?, *, +, {}) that
are greedy rather than the whole pattern; Perl prefers local greed and immediate gratification
to overall greed. To get non-greedy versions of the same quantifiers, use (??, *?,
+?, {}?).
An example:
|
Notice how the second substitution stopped matching as soon as it encountered "y ".
The *? quantifier effectively tells the regular expression engine to find a match
as quickly as possible and pass control on to whatever is next in line, like you would if you
were playing hot potato.
Use the split function:
|
Note that this isn't really a word in the English sense; it's just chunks of consecutive non-whitespace characters.
To work with only alphanumeric sequences (including underscores), you might consider
|
To do this, you have to parse out each word in the input stream. We'll pretend that by word you mean chunk of alphabetics, hyphens, or apostrophes, rather than the non-whitespace chunk idea of a word given in the previous question:
|
If you wanted to do the same thing for lines, you wouldn't need a regular expression:
|
If you want these output in a sorted order, see perlfaq4: ``How do I sort a hash (optionally by value instead of key)?''.
See the module String::Approx available from CPAN.
The following is extremely inefficient:
|
That's because Perl has to recompile all those patterns for each of the lines of the file. As
of the 5.005 release, there's a much better approach, one which makes use of the new qr//
operator:
|
\b work for me?Two common misconceptions are that \b is a synonym for \s+ and that
it's the edge between whitespace characters and non-whitespace characters. Neither is correct. \b
is the place between a \w character and a \W character (that is, \b
is the edge of a "word"). It's a zero-width assertion, just like ^, $,
and all the other anchors, so it doesn't consume any characters. perlre describes the behavior of all
the regex metacharacters.
Here are examples of the incorrect application of \b, with fixes:
|
Although they may not do what you thought they did, \b and \B can
still be quite useful. For an example of the correct use of \b, see the example of
matching duplicate words over multiple lines.
An example of using \B is the pattern \Bis\B. This will find
occurrences of "is" on the insides of words only, as in "thistle", but not
"this" or "island".
Once Perl sees that you need one of these variables anywhere in the program, it provides them on each and every pattern match. The same mechanism that handles these provides for the use of $1, $2, etc., so you pay the same price for each regex that contains capturing parentheses. If you never use $&, etc., in your script, then regexes without capturing parentheses won't be penalized. So avoid $&, $', and $` if you can, but if you can't, once you've used them at all, use them at will because you've already paid the price. Remember that some algorithms really appreciate them. As of the 5.005 release. the $& variable is no longer "expensive" the way the other two are.
\G
in a regular expression?The notation \G is used in a match or substitution in conjunction with the /g
modifier to anchor the regular expression to the point just past where the last match occurred,
i.e. the pos() point. A failed match resets the position of \G unless the /c
modifier is in effect. \G can be used in a match without the /g
modifier; it acts the same (i.e. still anchors at the pos() point) but of course only matches
once and does not update pos(), as non-/g expressions never do. \G in
an expression applied to a target string that has never been matched against a /g
expression before or has had its pos() reset is functionally equivalent to \A,
which matches at the beginning of the string.
For example, suppose you had a line of text quoted in standard mail and Usenet notation,
(that is, with leading > characters), and you want change each leading >
into a corresponding :. You could do so in this way:
|
Or, using \G, the much simpler (and faster):
|
A more sophisticated use might involve a tokenizer. The following lex-like example is
courtesy of Jeffrey Friedl. It did not work in 5.003 due to bugs in that release, but does work
in 5.004 or better. (Note the use of /c, which prevents a failed match with /g
from resetting the search position back to the beginning of the string.)
|
Of course, that could have been written as
|
but then you lose the vertical alignment of the regular expressions.
While it's true that Perl's regular expressions resemble the DFAs (deterministic finite automata) of the egrep(1) program, they are in fact implemented as NFAs (non-deterministic finite automata) to allow backtracking and backreferencing. And they aren't POSIX-style either, because those guarantee worst-case behavior for all cases. (It seems that some people prefer guarantees of consistency, even when what's guaranteed is slowness.) See the book "Mastering Regular Expressions" (from O'Reilly) by Jeffrey Friedl for all the details you could ever hope to know on these matters (a full citation appears in perlfaq2).
The problem is that both grep and map build a return list, regardless of the context. This means you're making Perl go to the trouble of building a list that you then just throw away. If the list is large, you waste both time and space. If your intent is to iterate over the list then use a for loop for this purpose.
Starting from Perl 5.6 Perl has had some level of multibyte character support. Perl 5.8 or later is recommended. Supported multibyte character repertoires include Unicode, and legacy encodings through the Encode module. See perluniintro, perlunicode, and Encode.
If you are stuck with older Perls, you can do Unicode with the Unicode::String
module, and character conversions using the Unicode::Map8 and Unicode::Map
modules. If you are using Japanese encodings, you might try using the jperl 5.005_03.
Finally, the following set of approaches was offered by Jeffrey Friedl, whose article in issue #5 of The Perl Journal talks about this very matter.
Let's suppose you have some weird Martian encoding where pairs of ASCII uppercase letters encode single Martian letters (i.e. the two bytes "CV" make a single Martian letter, as do the two bytes "SG", "VS", "XX", etc.). Other bytes represent single characters, just like ASCII.
So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
Now, say you want to search for the single character /GX/. Perl doesn't know
about Martian, so it'll find the two bytes "GX" in the "I am CVSGXX!"
string, even though that character isn't there: it just looks like it is because "SG"
is next to "XX", but there's no real "GX". This is a big problem.
Here are a few ways, all painful, to deal with it:
|
Or like this:
|
Or like this:
|
Or like this:
|
There are many double- (and multi-) byte encodings commonly used these days. Some versions of these have 1-, 2-, 3-, and 4-byte characters, all mixed.
Well, if it's really a pattern, then just use
|
Alternatively, since you have no guarantee that your user entered a valid regular expression, trap the exception this way:
|
If all you really want to search for a string, not a pattern, then you should either use the
index() function, which is made for string searching, or if you can't be disabused of using a
pattern match on a non-pattern, then be sure to use \Q...\E,
documented in perlre.
|
Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington. All rights reserved.
This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.
Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.
|
|
© 2002-2004 Active-Venture.com Web Site Hosting Service |
|
|
|
|
| [ All parts should go together without forcing. You must remember that the parts you are reassembling were disassembled by you. Therefore, if you can't get them together again, there must be a reason. By all means, do not use a hammer. ] | |
|
|
|
Disclaimer: This
documentation is provided only for the benefits of our web hosting customers.
|