home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 2 / RISC_DISC_2.iso / pd_share / utilities / cli / perl / !Perl / Manual / perlre < prev    next >
Encoding:
Text File  |  1995-04-18  |  15.1 KB  |  332 lines

  1. <!-- $RCSfile$$Revision$$Date$ -->
  2. <!-- $Log$ -->
  3. <HTML>
  4. <TITLE> PERLRE </TITLE>
  5. <h2>NAME</h2>
  6. perlre - Perl regular expressions
  7. <p><h2>DESCRIPTION</h2>
  8. For a description of how to use regular expressions in matching
  9. operations, see 
  10. <A HREF="perlfunc.html#perlfunc_171">m//</A>
  11.  and 
  12. <A HREF="perlfunc.html#perlfunc_212">s///</A>
  13.  in 
  14. <A HREF="perlop.html">
  15. the perlop manpage</A>
  16. .  The matching operations can
  17. have various modifiers, some of which relate to the interpretation of
  18. the regular expression inside.  These are:
  19. <p><pre>
  20.         i   Do case-insensitive pattern matching.
  21.         m   Treat string as multiple lines.
  22.         s   Treat string as single line.
  23.         x   Use extended regular expressions.
  24. </pre>
  25. These are usually written as "the <B>/x</B> modifier", even though the delimiter
  26. in question might not actually be a slash.  In fact, any of these
  27. modifiers may also be embedded within the regular expression itself using
  28. the new <B>(?...)</B> construct.  See below.
  29. <p>The <B>/x</B> modifier itself needs a little more explanation.  It tells the
  30. regular expression parser to ignore whitespace that is not backslashed
  31. or within a character class.  You can use this to break up your regular
  32. expression into (slightly) more readable parts.  Together with the
  33. capability of embedding comments described later, this goes a long
  34. way towards making Perl 5 a readable language.  See the C comment
  35. deletion code in 
  36. <A HREF="perlop.html">
  37. the perlop manpage</A>
  38. .
  39. <p><h3>Regular Expressions</h3>
  40. The patterns used in pattern matching are regular expressions such as
  41. those supplied in the Version 8 regexp routines.  (In fact, the
  42. routines are derived (distantly) from Henry Spencer's freely
  43. redistributable reimplementation of the V8 routines.)
  44. See 
  45. <A HREF="perlre.html#perlre_339">Version 8 Regular Expressions</A>
  46.  for details.
  47. <p>In particular the following metacharacters have their standard <I>egrep</I>-ish
  48. meanings:
  49. <p><pre>
  50.         \       Quote the next metacharacter
  51.         ^       Match the beginning of the line
  52.         .       Match any character (except newline)
  53.         $       Match the end of the line
  54.         |       Alternation
  55.         ()      Grouping
  56.         []      Character class
  57. </pre>
  58. By default, the "^" character is guaranteed to match only at the
  59. beginning of the string, the "$" character only at the end (or before the
  60. newline at the end) and Perl does certain optimizations with the
  61. assumption that the string contains only one line.  Embedded newlines
  62. will not be matched by "^" or "$".  You may, however, wish to treat a
  63. string as a multi-line buffer, such that the "^" will match after any
  64. newline within the string, and "$" will match before any newline.  At the
  65. cost of a little more overhead, you can do this by using the /m modifier
  66. on the pattern match operator.  (Older programs did this by setting 
  67. <A HREF="perlvar.html#perlvar_382">$*</A>
  68. ,
  69. but this practice is deprecated in Perl 5.)
  70. <p>To facilitate multi-line substitutions, the "." character never matches a
  71. newline unless you use the <B>/s</B> modifier, which tells Perl to pretend
  72. the string is a single line--even if it isn't.  The <B>/s</B> modifier also
  73. overrides the setting of 
  74. <A HREF="perlvar.html#perlvar_382">$*</A>
  75. , in case you have some (badly behaved) older
  76. code that sets it in another module.
  77. <p>The following standard quantifiers are recognized:
  78. <p><pre>
  79.         *          Match 0 or more times
  80.         +          Match 1 or more times
  81.         ?          Match 1 or 0 times
  82.         {n}    Match exactly n times
  83.         {n,}   Match at least n times
  84.         {n,m}  Match at least n but not more than m times
  85. </pre>
  86. (If a curly bracket occurs in any other context, it is treated
  87. as a regular character.)  The "*" modifier is equivalent to <B>{0,}</B>, the "+"
  88. modifier to <B>{1,}</B>, and the "?" modifier to <B>{0,1}</B>.  There is no limit to the
  89. size of n or m, but large numbers will chew up more memory. 
  90. <p>By default, a quantified subpattern is "greedy", that is, it will match as
  91. many times as possible without causing the rest pattern not to match.  The
  92. standard quantifiers are all "greedy", in that they match as many
  93. occurrences as possible (given a particular starting location) without
  94. causing the pattern to fail.  If you want it to match the minimum number
  95. of times possible, follow the quantifier with a "?" after any of them.
  96. Note that the meanings don't change, just the "gravity":
  97. <p><pre>
  98.         *?         Match 0 or more times
  99.         +?         Match 1 or more times
  100.         ??         Match 0 or 1 time
  101.         {n}?   Match exactly n times
  102.         {n,}?  Match at least n times
  103.         {n,m}? Match at least n but not more than m times
  104. </pre>
  105. Since patterns are processed as double quoted strings, the following
  106. also work:
  107. <p><pre>
  108.         \t              tab
  109.         \n              newline
  110.         \r              return
  111.         \f              form feed
  112.         \v              vertical tab, whatever that is
  113.         \a              alarm (bell)
  114.         \e              escape
  115.         \033    octal char
  116.         \x1b    hex char
  117.         \c[             control char
  118.         \l              lowercase next char
  119.         \u              uppercase next char
  120.         \L              lowercase till \E
  121.         \U              uppercase till \E
  122.         \E              end case modification
  123.         \Q              quote regexp metacharacters till \E
  124. </pre>
  125. In addition, Perl defines the following:
  126. <p><pre>
  127.         \w      Match a "word" character (alphanumeric plus "_")
  128.         \W      Match a non-word character
  129.         \s      Match a whitespace character
  130.         \S      Match a non-whitespace character
  131.         \d      Match a digit character
  132.         \D      Match a non-digit character
  133. </pre>
  134. Note that <B>\w</B> matches a single alphanumeric character, not a whole
  135. word.  To match a word you'd need to say <B>\w+</B>.  You may use <B>\w</B>, <B>\W</B>, <B>\s</B>,
  136. <B>\S</B>, <B>\d</B> and <B>\D</B> within character classes (though not as either end of a
  137. range).
  138. <p>Perl defines the following zero-width assertions:
  139. <p><pre>
  140.         \b      Match a word boundary
  141.         \B      Match a non-(word boundary)
  142.         \A      Match only at beginning of string
  143.         \Z      Match only at end of string
  144.         \G      Match only where previous m//g left off
  145. </pre>
  146. A word boundary (<B>\b</B>) is defined as a spot between two characters that
  147. has a <B>\w</B> on one side of it and and a <B>\W</B> on the other side of it (in
  148. either order), counting the imaginary characters off the beginning and
  149. end of the string as matching a <B>\W</B>.  (Within character classes <B>\b</B>
  150. represents backspace rather than a word boundary.)  The <B>\A</B> and <B>\Z</B> are
  151. just like "^" and "$" except that they won't match multiple times when the
  152. <B>/m</B> modifier is used, while "^" and "$" will match at every internal line
  153. boundary.
  154. <p>When the bracketing construct <B>( ... )</B> is used, \<digit> matches the
  155. digit'th substring.  (Outside of the pattern, always use "$" instead of
  156. "\" in front of the digit.  The scope of $<digit> (and 
  157. <A HREF="perlvar.html#perlvar_376">$`</A>
  158. , <B>$&</B>, and <B>$')</B>
  159. extends to the end of the enclosing BLOCK or eval string, or to the
  160. next pattern match with subexpressions.  
  161. If you want to
  162. use parentheses to delimit subpattern (e.g. a set of alternatives) without
  163. saving it as a subpattern, follow the ( with a ?.
  164. The \<digit> notation
  165. sometimes works outside the current pattern, but should not be relied
  166. upon.)  You may have as many parentheses as you wish.  If you have more
  167. than 9 substrings, the variables $10, $11, ... refer to the
  168. corresponding substring.  Within the pattern, \10, \11, etc. refer back
  169. to substrings if there have been at least that many left parens before
  170. the backreference.  Otherwise (for backward compatibilty) \10 is the
  171. same as \010, a backspace, and \11 the same as \011, a tab.  And so
  172. on.  (\1 through \9 are always backreferences.)
  173. <p>
  174. <A HREF="perlvar.html#perlvar_380">$+</A>
  175.  returns whatever the last bracket match matched.  <B>$&</B> returns the
  176. entire matched string.  ($0 used to return the same thing, but not any
  177. more.)  
  178. <A HREF="perlvar.html#perlvar_376">$`</A>
  179.  returns everything before the matched string.  
  180. <A HREF="perlvar.html#perlvar_378">$'</A>
  181.  returns
  182. everything after the matched string.  Examples:
  183. <p><pre>
  184.         s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words
  185. </pre>
  186. <pre>
  187.         if (/Time: (..):(..):(..)/) {
  188.         $hours = $1;
  189.         $minutes = $2;
  190.         $seconds = $3;
  191.         }
  192. </pre>
  193. You will note that all backslashed metacharacters in Perl are
  194. alphanumeric, such as <B>\b</B>, <B>\w</B>, <B>\n</B>.  Unlike some other regular expression
  195. languages, there are no backslashed symbols that aren't alphanumeric.
  196. So anything that looks like \\, \(, \), \<, \>, \{, or \} is always
  197. interpreted as a literal character, not a metacharacter.  This makes it
  198. simple to quote a string that you want to use for a pattern but that
  199. you are afraid might contain metacharacters.  Simply quote all the
  200. non-alphanumeric characters:
  201. <p><pre>
  202.         $pattern =~ s/(\W)/\\$1/g;
  203. </pre>
  204. You can also use the built-in quotemeta() function to do this.
  205. An even easier way to quote metacharacters right in the match operator
  206. is to say 
  207. <p><pre>
  208.         /$unquoted\Q$quoted\E$unquoted/
  209. </pre>
  210. Perl 5 defines a consistent extension syntax for regular expressions.
  211. The syntax is a pair of parens with a question mark as the first thing
  212. within the parens (this was a syntax error in Perl 4).  The character
  213. after the question mark gives the function of the extension.  Several
  214. extensions are already supported:
  215. <p>
  216. <dl>
  217.  
  218. <dt><b><A NAME="perlre_334">(?#text)</A></b>
  219. <dd>
  220. A comment.  The text is ignored.
  221. <p></dd>
  222.  
  223. <dt><b><A NAME="perlre_335">(?:regexp)</A></b>
  224. <dd>
  225. This groups things like "()" but doesn't make backrefences like "()" does.  So
  226. <p></dd>
  227. <pre>
  228.         split(/\b(?:a|b|c)\b/)
  229. </pre>
  230. is like
  231. <p><pre>
  232.         split(/\b(a|b|c)\b/)
  233. </pre>
  234. but doesn't spit out extra fields.
  235. <p>
  236. <dt><b><A NAME="perlre_336">(?=regexp)</A></b>
  237. <dd>
  238. A zero-width positive lookahead assertion.  For example, <B>/\w+(?=\t)/</B>
  239. matches a word followed by a tab, without including the tab in <B>$&</B>.
  240. <p></dd>
  241.  
  242. <dt><b><A NAME="perlre_337">(?!regexp)</A></b>
  243. <dd>
  244. A zero-width negative lookahead assertion.  For example <B>/foo(?!bar)/</B>
  245. matches any occurrence of "foo" that isn't followed by "bar".  Note
  246. however that lookahead and lookbehind are NOT the same thing.  You cannot
  247. use this for lookbehind: <B>/(?!foo)bar/</B> will not find an occurrence of
  248. "bar" that is preceded by something which is not "foo".  That's because
  249. the <B>(?!foo)</B> is just saying that the next thing cannot be "foo"--and
  250. it's not, it's a "bar", so "foobar" will match.  You would have to do
  251. something like <B>/(?foo)...bar/</B> for that.   We say "like" because there's
  252. the case of your "bar" not having three characters before it.  You could
  253. cover that this way: <B>/(?:(?!foo)...|^..?)bar/</B>.  Sometimes it's still 
  254. easier just to say:
  255. <p></dd>
  256. <pre>
  257.         if (/foo/ && $` =~ /bar$/) 
  258. </pre>
  259.  
  260. <dt><b><A NAME="perlre_338">(?imsx)</A></b>
  261. <dd>
  262. One or more embedded pattern-match modifiers.  This is particularly
  263. useful for patterns that are specified in a table somewhere, some of
  264. which want to be case sensitive, and some of which don't.  The case
  265. insensitive ones merely need to include <B>(?i)</B> at the front of the
  266. pattern.  For example:
  267. <p></dd>
  268. <pre>
  269.         $pattern = "foobar";
  270.         if ( /$pattern/i ) 
  271. </pre>
  272. <pre>
  273.         # more flexible:
  274. </pre>
  275. <pre>
  276.         $pattern = "(?i)foobar";
  277.         if ( /$pattern/ ) 
  278. </pre>
  279.  
  280. </dl>
  281.  
  282. The specific choice of question mark for this and the new minimal
  283. matching construct was because 1) question mark is pretty rare in older
  284. regular expressions, and 2) whenever you see one, you should stop
  285. and "question" exactly what is going on.  That's psychology...
  286. <p><h3>Version 8 Regular Expressions</h3>
  287. In case you're not familiar with the "regular" Version 8 regexp
  288. routines, here are the pattern-matching rules not described above.
  289. <p>Any single character matches itself, unless it is a <I>metacharacter</I>
  290. with a special meaning described here or above.  You can cause
  291. characters which normally function as metacharacters to be interpreted
  292. literally by prefixing them with a "\" (e.g. "\." matches a ".", not any
  293. character; "\\" matches a "\").  A series of characters matches that
  294. series of characters in the target string, so the pattern <B>blurfl</B>
  295. would match "blurfl" in the target string.
  296. <p>You can specify a character class, by enclosing a list of characters
  297. in <B>[]</B>, which will match any one of the characters in the list.  If the
  298. first character after the "[" is "^", the class matches any character not
  299. in the list.  Within a list, the "-" character is used to specify a
  300. range, so that <B>a-z</B> represents all the characters between "a" and "z",
  301. inclusive.
  302. <p>Characters may be specified using a metacharacter syntax much like that
  303. used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return,
  304. "\f" a form feed, etc.  More generally, \<I>nnn</I>, where <I>nnn</I> is a string
  305. of octal digits, matches the character whose ASCII value is <I>nnn</I>.
  306. Similarly, \x<I>nn</I>, where <I>nn</I> are hexidecimal digits, matches the
  307. character whose ASCII value is <I>nn</I>. The expression \c<I>x</I> matches the
  308. ASCII character control-<I>x</I>.  Finally, the "." metacharacter matches any
  309. character except "\n" (unless you use <B>/s</B>).
  310. <p>You can specify a series of alternatives for a pattern using "|" to
  311. separate them, so that <B>fee|fie|foe</B> will match any of "fee", "fie",
  312. or "foe" in the target string (as would <B>f(e|i|o)e</B>).  Note that the
  313. first alternative includes everything from the last pattern delimiter
  314. ("(", "[", or the beginning of the pattern) up to the first "|", and
  315. the last alternative contains everything from the last "|" to the next
  316. pattern delimiter.  For this reason, it's common practice to include
  317. alternatives in parentheses, to minimize confusion about where they
  318. start and end.  Note also that the pattern <B>(fee|fie|foe)</B> differs
  319. from the pattern <B>[fee|fie|foe]</B> in that the former matches "fee",
  320. "fie", or "foe" in the target string, while the latter matches
  321. anything matched by the classes <B>[fee]</B>, <B>[fie]</B>, or <B>[foe]</B> (i.e.
  322. the class <B>[feio]</B>).
  323. <p>Within a pattern, you may designate subpatterns for later reference by
  324. enclosing them in parentheses, and you may refer back to the <I>n</I>th
  325. subpattern later in the pattern using the metacharacter \<I>n</I>. 
  326. Subpatterns are numbered based on the left to right order of their
  327. opening parenthesis.  Note that a backreference matches whatever
  328. actually matched the subpattern in the string being examined, not the
  329. rules for that subpattern.  Therefore, <B>([0|0x])\d*\s\1\d*</B> will
  330. match "0x1234 0x4321",but not "0x1234 01234", since subpattern 1
  331. actually matched "0x", even though the rule <B>[0|0x]</B> could
  332. potentially match the leading 0 in the second number.<p>