Regular expressions, often abbreviated as “regex”, are used for pattern matching and manipulation of text strings. Python provides the `re` module to handle regular expression.
Here’s how to perform common tasks with regular expressions in Python:
1. Importing the module: \`\`\`python import re \`\`\`
1. Searching for a pattern in a string: \`\`\`python string = ‘Hello, World!‘ pattern = ‘World‘ match = re.search(pattern, string) if match: print(‘Found’) \`\`\` It prints ‘Found’ if the pattern “World” exists in the string.
1. Using special sequences:
– `\d` : Matches any decimal digit; equivalent to the set [0-9]. – `D` : Matches any non-digit character. – `.` : Matches any character except newline. \`\`\`python string = ‘John Doe, Age: 30‘ pattern = ‘\d+’ # Matches one or more digits match = re.search(pattern, string) if match: print(match.group()) # Outputs: 30 \`\`\`1. Splitting a string by a pattern: \`\`\`python string = ‘John,Doe,30‘ pattern = ‘,‘ split\_string = re.split(pattern, string) print(split\_string) # Outputs: [‘John’, ‘Doe’, ‘30’] \`\`\`
1. Replacing text: \`\`\`python string = ‘Hello, World!‘ pattern = ‘World‘ replace\_with = ‘Friend‘ new_string = re.sub(pattern, replace_with, string) print(new\_string) # Outputs: ‘Hello, Friend!‘ \`\`\`
1. Compiling a regular expression for repeated use: \`\`\`python pattern = re.compile(‘\d+’) match_in_string1 = pattern.search(‘Hello, I am 25 years old’) match_in_string2 = pattern.search(‘I have 2 apples’) print(match_in_string1.group()) # Outputs: ‘25‘ print(match_in_string2.group()) # Outputs: ‘2‘ \`\`\`
For more complex pattern matching, you can use square brackets `[]` to specify a set of characters, parentheses `()` to group expressions, and more. For full details, check the Python `re` module documentation.