HOWTO-regexps.htm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Regular Expressions explained</title>
  5. <meta charset="utf-8">
  6. <link href="./manual.css" rel="stylesheet" type="text/css">
  7. </head>
  8. <body>
  9. <div id="container">
  10. <header>
  11. <h3>Found at: http://publish.ez.no/article/articleprint/11/</h3>
  12. <h1>Regular Expressions explained</h1>
  13. <p class="byline">
  14. <span>Author: <a href="http://publish.ez.no/article/author/view/26">Jan Borsodi</a></span>
  15. <span class="page-date">Publishing date: 30.10.2000 18:02</span>
  16. </p>
  17. </header>
  18. <section>
  19. This article will give you an introduction to the world of <i>regular expressions</i>. I'll start off with explaining what regular expressions are and introduce it's syntax, then some examples with varying complexity and last a list of tools which use <i>regular expressions</i>.
  20. <p style="color: #f00">
  21. [Note: Puppy has a regular expression evaluation and learning tool in the Utilities menu]
  22. </p>
  23. </section>
  24. <section>
  25. <h2>Concept</h2>
  26. <p>
  27. A <i>regular expression</i> is a text pattern consisting of a combination of alphanumeric characters and special characters known as metacharacters. A close relative is in fact the <i>wildcard expression</i> which are often used in file management. The pattern is used to match against text strings. The result of a match is either successful or not, however when a match is successful not all of the pattern must match, this is explained later in the article.
  28. </p>
  29. <p>
  30. You'll find that <i>regular expressions</i> are used in three different ways: Regular text match, search and replace and splitting. The latter is basically the same as the reverse match ie. everything the <i>regular expression</i> did not match.
  31. </p>
  32. <p>
  33. <i>Regular expressions</i> are often simply called regexps or RE, but for consistency I'll be referring to it with its full name.
  34. </p>
  35. <p>
  36. Due to the versatility of the <i>regular expression</i> it is widely used in text processing and parsing. UNIX users are probably familiar with them through the use of the programs, <i>grep</i>, <i>sed</i>, <i>awk</i> and <i>ed</i>. Text editors such as <i>(X)Emacs</i> and <i>vi</i> also use them heavily. Probably the most known use of <i>regular expressions</i> are in the programming language Perl; you'll find that Perl sports the most advanced <i>regular expression</i> implementation to this day.
  37. </p>
  38. </section>
  39. <section>
  40. <h2>Usage</h2>
  41. <p>
  42. Now you're probably wondering why you should bother to learn <i>regular expressions</i>. Well, if you're a normal computer user your benefits from using them are somewhat small; however if you're either a developer or a system administrator you'll find that knowing <i>regular expressions</i> will make your (professional) life so much better.
  43. </p>
  44. <p>
  45. Developers can use them to parse text files, fix up code and other wonders. System administrators can use them to search through logs, automate boring tasks and sniff the network traffic for unauthorized activity.
  46. </p>
  47. <p>
  48. Actually I would go so far as to say it's a crime for a System Administrator not to have <b>any</b> knowledge of <i>regular expressions</i>.
  49. </p>
  50. </section>
  51. <section>
  52. <h2>Quantifiers</h2>
  53. <section>
  54. <p>
  55. Before I start explaining the syntax you might want to jump to the last page to learn which programs you can use to test out the examples in this article.
  56. </p>
  57. <p>
  58. The contents of an expression are, as explained earlier, a combination of alphanumeric characters and metacharacters. An alphanumeric character is either a letter from the alphabet
  59. <code>abc</code>
  60. or a number
  61. <code>123</code>
  62. </p>
  63. <p>
  64. Actually in the world of regular expressions any character which is not a metacharacter will match itself (often called literal characters), however a lot of the time you're mostly concerned with the alphanumeric characters. A very special character is the backslash <b>\</b>; this turns any metacharacters into literal characters, and alphanumeric characters into a sort of metacharacter or sequence. The metacharacters are:
  65. <code>\ | ( ) [ { ^ $ * + ? . &lt; &gt;</code>
  66. With that said, normal characters don't sound too interesting, so let's jump to our very first meta characters.
  67. </p>
  68. </section>
  69. <section>
  70. <p>
  71. The punctuation mark, or dot, <b>.</b> needs explaining first since it often leads to confusion. This character will not, as many might think, match the punctuation in a line, it is instead a special meta character which matches any character. Using this were you wanted to find the end of the line or the decimal in a floating number will lead to strange results. As explained above, you need to backslashify it to get the literal meaning. For instance take this expression
  72. <code>1.23</code>
  73. will match the number 1.23 in a text as you might have guessed, but it will also match these next lines:
  74. <code>
  75. 1x23<br>
  76. 1 23<br>
  77. 1-23
  78. </code>
  79. To make the expression <b>only</b> match the floating number we change it to
  80. <code>1\.23</code>
  81. Remember this, it's very important. Now with that said we can get the show going.
  82. </p>
  83. </section>
  84. <section>
  85. <p>
  86. Two heavily recurring metacharacters are
  87. <code>* and +</code>
  88. They are called quantifiers and tells the engine to look for several occurrences of a character; the quantifier always precedes the character at hand. The <b>*</b> character matches zero or more occurrences of the character in a row, the <b>+</b> character is similar but matches one or more.
  89. </p>
  90. <p>
  91. So if you decided to find words which had the character <i>c</i> in it, you might be tempted to write
  92. <code>c*</code>
  93. What might come as a surprise to you is that you will find an enormous number of matches, even words with no c in it will match. How so you ask, well the answer is simple. Recall that the <b>*</b> character matches <b>zero</b> or more characters, well that's exactly what you did, zero characters.<br>
  94. You see in <i>regular expressions</i> you have the possibility to match what is called <b>the empty string</b>, which is simply a string with zero size. This empty string can actually be found in all texts, for instance the word:
  95. <code>go</code>
  96. contains three empty strings. They are contained at the position right before the <b>g</b>, in between the <b>g</b> and the <b>o</b> and after the <b>o</b>. And an empty string contains exactly <b>one</b> empty string. At first this might seem like a really silly thing to do but you'll learn later on how this is used in more complex expressions.<br>
  97. So with this knowledge we might want to change our expression to:
  98. <code>c+</code>
  99. and voila we get only words with c in them.
  100. </p>
  101. </section>
  102. <section>
  103. <p>
  104. The next metacharacter you'll learn is:
  105. <code>?</code>
  106. This simply tells the engine to either match the character or not (zero or one). For instance the expression:
  107. <code>cows?</code>
  108. will match any of these lines:
  109. <code>
  110. cow<br>
  111. cows
  112. </code>
  113. </p>
  114. </section>
  115. <section>
  116. <p>
  117. These three metacharacters are simply a specialized scenario for the more generalized quantifier
  118. <code>{n,m}</code>
  119. The <b>n</b> and <b>m</b> are respectively the minimum and maximum size for the quantifier. For instance
  120. <code>{1,5}</code>
  121. means match one or up to five characters. You can also skip m to allow for infinite match:
  122. <code>{1,}</code>
  123. which matches one or more characters. This is exactly what the <b>+</b> character does. So now you see the connection, <b>*</b> is equal to <b>{0,}</b>, <b>+</b> is equal to <b>{1,}</b> and <b>?</b> is equal to <b>{0,1}</b>.<br />
  124. The last thing you can do with the quantifier is to also skip the comma,
  125. <code>{5}</code>
  126. which means to match 5 characters, no more no less.
  127. </p>
  128. </section>
  129. </section>
  130. <section>
  131. <h2>Assertions</h2>
  132. <p>
  133. The next type of metacharacters are assertions, these will match if a given assertion is true.
  134. </p>
  135. <section>
  136. <p>
  137. The first pair of assertions are
  138. <code>^ and $</code>
  139. which match the beginning of the line and the end of the line. Note that some <i>regular expression</i> implementations allows you to change their behavior so that they will instead match the beginning of the text and the end of the text. These assertions always match a zero length string, or in other words they match a position. For instance if you wrote this expression:
  140. <code>^The</code>
  141. it would match any line which began with the word <b>The</b>.
  142. </p>
  143. </section>
  144. <section>
  145. <p>
  146. The next assertion characters match at the beginning and end of a word, they are:
  147. <code>&lt; and &gt;</code>
  148. they come in handy when you want to match a word precisely, for instance:
  149. <code>cow</code>
  150. would match any of the following words:
  151. <code>
  152. cow<br>
  153. coward<br>
  154. cowage<br>
  155. cowboy<br>
  156. cowl
  157. </code>
  158. a small change to the expression:
  159. <code>&lt;cow&gt;</code>
  160. and you'll only match the word <b>cow</b> in the text.
  161. </p>
  162. </section>
  163. <section>
  164. <p>
  165. One last thing to be said is that all literal characters are in fact assertions themselves, the difference between them and the ones above is that literal ones have a size. So for cleanliness' sake we only use the word assertions for those that are zero-width.
  166. </p>
  167. </section>
  168. </section>
  169. <section>
  170. <h2>Groups and alternation</h2>
  171. <p>
  172. One thing you might have noticed when we explained quantifiers is that they only worked on the character to the left, since this pretty much limits our expressions I'll explain other uses for quantifiers. Quantifiers can also be used on metacharacters, using them on assertions is silly since they are zero-width and matching one, two, three or more of them doesn't do any good. However the grouping and sequence metacharacters are perfect for being quantified. Let's first start with grouping.
  173. </p>
  174. <section>
  175. <p>
  176. You can form groups, or subexpressions as they are frequently called, by using the begin and end parenthesis characters:
  177. <code>( and )</code>
  178. The <b>(</b> starts the subexpression and the <b>)</b> ends it. It is also possible to have one or more subexpressions inside a subexpressions. The subexpression will match if the contents match. So mixing this with quantifiers and assertions you can do:
  179. <code>( ?ho)+</code>
  180. which matches all of the following lines:
  181. <code>
  182. ho<br>
  183. ho ho<br>
  184. ho ho ho<br>
  185. hohoho
  186. </code>
  187. Another use for the subexpressions are to extract a portion of the match if it matches, this is often used in conjunction with sequences which is discussed later.
  188. </p>
  189. <p>
  190. You can also use the result of a subexpression for what is called a back reference. A back reference is given by using a backslashified digit, only a single non-zero digit, this leaves you with nine back references.<br> matched (except that {article_contents_1} matches a null character). To find the number of the subexpression count the left parentheses from the left.
  191. </p>
  192. <p>
  193. The use for back references are somewhat limited, especially since you only have nine of them, but on some rare occasion you might need it. Note some <i>regular expression</i> implementations can use multi-digit numbers as long as they don't start with a 0.
  194. </p>
  195. </section>
  196. <section>
  197. <p>
  198. Next are alternations which allow you to match one of many words; the alternation character is
  199. <code>|</code>
  200. a sample usage is:
  201. <code>Bill|Linus|Steve|Larry</code>
  202. would match either Bill, Linus, Steve or Larry, and mixing this with subexpressions and quantifiers we can do:
  203. <code>cow(ard|age|boy|l)?</code>
  204. which matches any of the following words but none other
  205. <code>
  206. cow<br>
  207. coward<br>
  208. cowage<br>
  209. cowboy<br>
  210. cowl<br>
  211. </code>
  212. I mentioned earlier in the article that not all of the expression must match for the match to be successful, this can happen when you're using subexpressions together with alternations. For instance
  213. <code>((Donald|Dolly) Duck)|(Scrooge McDuck)</code>
  214. As you see only the left or right top subexpression will match, not both, this is sometimes handy when you want to run a complex pattern in one subexpression and if it fails try another one.
  215. </p>
  216. </section>
  217. </section>
  218. <section>
  219. <h2>Sequences</h2>
  220. <section>
  221. <p>
  222. Last we have sequences which define sequences of characters which can match; sometimes you don't want match a word directly but rather something that resembles one. The sequence characters are
  223. <code>[ and ]</code>
  224. Any characters put inside the sequence brackets are treated as a literal character, even metacharacters. The only special characters are the <b>-</b> which denotes character ranges and the <b>^</b> which is used to negate a sequence. The sequence is somewhat similar with alternation, the similarity is that only one of the items listed will match. For instance
  225. <code>[a-z]</code>
  226. will match any small characters which are in the English alphabet (a to z). Another common sequence is
  227. <code>[a-zA-Z0-9]</code>
  228. which matches any small or capital characters in the English alphabet as well as numbers. Sequences are also mixed with quantifiers and assertions to produce more elaborate searches. For instance
  229. <code>&lt;[a-zA-Z]+&gt;</code>
  230. matches all whole words. This will match
  231. <code>
  232. cow<br>
  233. Linus<br>
  234. regular<br>
  235. expression
  236. </code>
  237. but will not match
  238. <code>
  239. 200<br>
  240. x-files<br>
  241. C++
  242. </code>
  243. </p>
  244. </section>
  245. <section>
  246. <p>
  247. Now what if you wanted to find anything but words? The expression
  248. <code>[^a-zA-Z0-9]+</code>
  249. would find any sequences of characters which does not contain the English
  250. alphabet or any numbers.
  251. </p>
  252. </section>
  253. <section>
  254. <p>
  255. Some implementations of <i>regular expressions</i> allows you to use
  256. shorthand versions for commonly used sequences, they are:
  257. <code>
  258. \d, a digit [0-9]
  259. \D, a non-digit [^0-9]<br>
  260. \w, a word (alphanumeric) [a-zA-Z0-9]<br>
  261. \W, a non-word [^a-zA-Z0-9]<br>
  262. \s, a whitespace [ \t\n\r\f]<br>
  263. \S, a non-whitespace [^ \t\n\r\f]
  264. </code>
  265. </p>
  266. </section>
  267. </section>
  268. <section>
  269. <h2>Wildcards</h2>
  270. <p>
  271. For people who have some knowledge with wildcards I'll give a brief explanation on how to convert them to <i>regular expressions</i>. After reading this article you probably have seen the similarities with wildcards. For instance
  272. <code>*.jpg</code>
  273. matches any text which end with .jpg. You can also specify brackets with characters, for instance
  274. <code>*.[ch]pp</code>
  275. matches any text which ends in .cpp or .hpp. Altogether very similar to regular expressions.
  276. </p>
  277. <section>
  278. <h3>Converting the * operator</h3>
  279. <p>
  280. The * means match zero or more of anything in wildcards, as we learned we do this is regular expression with the punctuation mark and the * quantifier. This gives
  281. <code>.*</code>
  282. Also remember to convert any punctuation marks from wildcards to be backslashified.
  283. </p>
  284. </section>
  285. <section>
  286. <h3>Converting the ? operator</h3>
  287. <p>
  288. The ? means match any character but do match <b>something</b>, this is exactly what the punctuation mark does.
  289. </p>
  290. </section>
  291. <section>
  292. <h3>Converting the [] operator</h3>
  293. <p>
  294. The square bracket can be used untouched since they have the same meaning going from wildcards to regular expressions.
  295. </p>
  296. </section>
  297. <section>
  298. <p>
  299. These leaves us with:<br>
  300. Replace any * characters with .*<br>
  301. Replace any ? characters with .<br>
  302. Leave square brackets as they are.<br>
  303. Replace any characters which are metacharacters with a backslashified variant.
  304. </p>
  305. </section>
  306. <section>
  307. <h3>Examples</h3>
  308. <p>
  309. <code>*.jpg</code>
  310. would be converted to
  311. <code>.*\.jpg</code>
  312. and
  313. <code>ez*.[ch]pp</code>
  314. would be converted to
  315. <code>ez.*\.[ch]pp</code>
  316. or alternatively
  317. <code>ez.*\.(cpp|hpp)</code>
  318. </p>
  319. </section>
  320. </section>
  321. <section>
  322. <h2>Examples</h2>
  323. <p>
  324. To really get to know <i>regular expressions</i> I've left some commonly used expressions on this page. Study them, experiment and try to understand exactly what they are doing.
  325. </p>
  326. <p>
  327. Email validity, will only match email addresses which are valid, for instance user@host.com
  328. <code>[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+</code>
  329. </p>
  330. <p>
  331. Email validity #2, matches email addresses with a name in front, for instance "Joe Doe &lt;user@host.com&gt;"
  332. <code>("?[a-zA-Z]+"?[ \t]*)+\&lt;[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+\&gt;</code>
  333. </p>
  334. <p>
  335. Protocol validity, matches web based protocols such as http://, ftp:// or https://
  336. <code>[a-z]+://</code>
  337. </p>
  338. <p>
  339. C/C++ includes, matches valid include statements in C/C++ files.
  340. <code>^#include[ \t]+[<"][^>"]+["&gt;]</code>
  341. </p>
  342. <p>
  343. C++ end of line comments
  344. <code>//.+$</code>
  345. </p>
  346. <p>
  347. C/C++ span line comments, it has one flaw, can you spot it?
  348. <code>/\*[^*]*\*/</code>
  349. </p>
  350. <p>
  351. Floating point numbers, matches simple floating point numbers of the kind 1.2 and 0.5
  352. <code>-?[0-9]+\.[0-9]+</code>
  353. </p>
  354. <p>
  355. Hexadecimal numbers, matches C/C++ style hex numbers, 0xcafebabe
  356. <code>0x[0-9a-fA-F]+</code>
  357. </p>
  358. </section>
  359. <section>
  360. <h2>Utilities</h2>
  361. <p>
  362. There exist several utilities which use regular expressions. I'll leave a list of them with a short description:
  363. </p>
  364. <section>
  365. <h3>grep</h3>
  366. <p>
  367. Grep searches named input files for lines containing a match to the given pattern. It can also be used to find files which contains a specific pattern, for instance:
  368. <code>grep -E "cow|vache" * &gt;/dev/null &amp;&amp; echo "Found a cow"</code>
  369. </p>
  370. <p>
  371. This utility is rather common on Linux distributions, but if you don't have it you can grab a version on <a href="http://www.gnu.org/gnulist/production/grep.html">the GNU page</a>
  372. </p>
  373. <p>
  374. A small tip is to enable extended regular expressions with the options -E, if not, a lot of the metacharacters explained in this article won't work.
  375. </p>
  376. </section>
  377. <section>
  378. <h3>sed</h3>
  379. <p>
  380. Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream.
  381. </p>
  382. <p>
  383. This utility is rather common on Linux distributions, but if you don't have it you can grab a version on <a href="http://www.gnu.org/gnulist/production/sed.html">the GNU page</a>
  384. </p>
  385. </section>
  386. <section>
  387. <h3>gawk</h3>
  388. <p>
  389. Gawk is the GNU Project's implementation of the AWK programming language. It conforms to the definition of the language in the POSIX 1003.2 Command Language And Utilities Standard.
  390. </p>
  391. <p>
  392. This is utility is rather common on Linux distributions, but if you don't have it you can grab a version on <a href="http://www.gnu.org/">the GNU page</a>
  393. </p>
  394. </section>
  395. </section>
  396. <section>
  397. <header><i>Regular expression</i> related links:</header>
  398. <ul>
  399. <li><a href="http://www.plover.com/~mjd/perl/NPC/index.html">Regular Expressions and NP-Completeness</a></li>
  400. <li><a href="http://www.cs.rochester.edu/u/leblanc/csc173/fa/re.html">Equivalence of Regular Expressions and Finite Automata</a></li>
  401. <li><a href="http://virtual.park.uga.edu/humcomp/perl/regex2a.html">Perl Regular Expression Tutorial</a></li>
  402. </ul>
  403. </section>
  404. </div>
  405. </body>
  406. </html>