Python: Use RegEx - Instructions with example
Related Videos: Python Tutorial: re Module - How to Write and Match Regular Expressions (Regex) (May 2024).
Regular expressions ("RegEx" for short) in Python make it much easier to search strings. You can find out how this works in this practical tip.
Use RegEx in Python
The regular expressions, i.e. regular expressions, are characters that are assigned a special function.
- You can use square brackets to specify a set of characters to check whether they appear in a string. For example, "[ab]" is used to check whether either a and / or b appear in the string.
- You can also use a hyphen to delimit a range: "[0-9]" includes the numbers from 0 to 9, for example.
- If you want to leave out a certain area, you can do this with a circumflex. For example, "[^ abc]" includes all chars except a, b, and c.
- With a point you can represent any single chars. The expression ".." would generate a match for "aa", also a match for "aaa", but two matches for "aaaa" (since two times two chars could be represented here).
- The circumflex is also very practical. You can use this to check whether a string starts with a certain combination of characters. For example, with "^ ab" all strings that start with "ab" create a match.
- Conversely, you can use the dollar sign to check whether a string ends with a specific char: "a $".
- Python has many other regular expressions. It's best to take a look at the documentation.
Regular expressions in Python: the re module
To be able to use the regular expressions, you need the (pre-installed) re-module.
- First import it with the "import re" command.
- Now you can use "result = re.match (" ^ a ... b $ ", " a111b ")" to check whether the string "a111b" begins with a, then follows three characters and ends with b.
- If this is the case, an object is output that describes the match in more detail.
- If the regular expression does not match the string, False is output. With "if result:" you can easily check whether the regular expression is correct.
Tip: You can find more programming tutorials on our Python programming language topic page. There we will show you, for example, how you can use the string replace function in Python.