The third subsection shows how to group subexpressions and how to capture matching text, and the final subsection shows how to use the language's assertions and flags to affect how regular expressions work. The second subsection shows how to quantify matches for example, match once, or match at least once, or match as many times as possible. The first subsection shows how to match individual characters or groups of characters for example, match a, or match b, or match either a or b.
This section looks at the regular expression language in four subsections.
Regular expressions are indicated in the text using bold, where they match in green, and captures are shown using highlighting. The article covers the complete regex language offered by the re module, including all the assertions and flags. Readers familiar with regular expressions who just want to learn how they work in Python could skip to the second section. The second section shows how to use regular expressions in the context of Python programming, drawing on all the material covered earlier. The first section of this article introduces and explains all the key regular expression concepts and shows pure regular expression syntax-it makes minimal reference to Python itself. More complex regexes consist of any number of quantified expressions, may include assertions, and may be influenced by flags. Splitting a string at each place the regex matches for example, splitting everywhere a colon ( :) or equal sign ( =) is encountered.Īt its simplest, a regular expression is an expression (for instance, a literal character), optionally followed by a quantifier. Replacing everywhere the regex matches with a string for example, finding bicycle or human powered vehicle and replacing either with bike. Locating substrings that can have more than one form for example, finding any of pet.png, pet.jpg, pet.jpeg, or pet.svg while avoiding carpet.png and similar. Checking whether a piece of text meets some criteria for example, a currency symbol followed by digits. It doesn't explicitly cover Python, but Python's re module offers very similar functionality to the Perl regular expression engine that the book covers in depth. A good book on regular expressions is Mastering Regular Expressions by Jeffrey E.