Difference between revisions of "Perl regex"

from HTYP, the free directory anyone can edit if they can prove to me that they're not a spambot
Jump to navigation Jump to search
(→‎Examples: more examples; fixed error in first example)
(→‎Details: more stuff)
Line 17: Line 17:
  
 
Operators used to invoke regex:
 
Operators used to invoke regex:
* =~ returns TRUE if pattern matches
+
* '''=~''' returns TRUE if pattern matches
* !~ returns FALSE if pattern matches
+
* '''!~''' returns FALSE if pattern matches
* s/''pattern''/''replacement''/ replaces ''pattern'' with ''replacement''
+
* '''s/'''<u>pattern</u>'''/'''<u>replacement</u>'''/'''''gi''; replaces ''pattern'' with ''replacement''
 +
** '''g''' (global) means repeat the pattern search until there are no more matches
 +
** '''i''' (insensitive) means alphabetic matches are checked case-insensitively
 +
* '''y/'''<u>searchlist</u>'''/'''<u>replacelist</u>'''/'''''d'': replaces each character found in <u>searchlist</u> with the corresponding character in <u>replacelist</u>
 +
** '''d''' just deletes matching characters
 +
* '''tr/''' is the same as '''y/'''
 +
 
 
==Examples==
 
==Examples==
 
* Replace "thingy" with "stuffs" in $string:
 
* Replace "thingy" with "stuffs" in $string:

Revision as of 21:05, 24 March 2006

Computing: Programming: Perl: regex

This article explains regular expressions in terms understandable to mere mortals, and also how to use them in Perl.

Related Articles

  • regex: manpage documentation

Details

Special characters in regex:

  • . = any character
  • * = 0 or more of previous character
  • ^ = following string begins the line (except [^...] means "not these characters")
  • $ = preceding string ends the line
  • [] = list of characters which can satisfy the match at this position
  • {} = # of repetitions of previous character
  • | = alternatives
  • + = 1 or more of previous character
  • a-b = range of characters from a to b (must be inside [] to be position-sensitive?)

Operators used to invoke regex:

  • =~ returns TRUE if pattern matches
  • !~ returns FALSE if pattern matches
  • s/pattern/replacement/gi; replaces pattern with replacement
    • g (global) means repeat the pattern search until there are no more matches
    • i (insensitive) means alphabetic matches are checked case-insensitively
  • y/searchlist/replacelist/d: replaces each character found in searchlist with the corresponding character in replacelist
    • d just deletes matching characters
  • tr/ is the same as y/

Examples

  • Replace "thingy" with "stuffs" in $string:
    • $string =~ s/thingy/stuffs/;
  • Keep only the part of $string before the final "/" (using "|" as the delimiter instead of "/"):
    • $string =~ s|(.*)/[^/]*|$1|;
  • ...before the final "-":
    • $string =~ s|(.*)-[^-]*|$1|;
  • ...before the final ".":
    • $string =~ s|(.*)\.[^\.]*|$1|;
  • ...after the final "."
    • $string =~ s|^.+\.(.+$)|$1|;