Basic Syntax
Regular expressions are composed of literal characters and metacharacters. Literal characters are those that match exactly with the same characters in the input text. Metacharacters, on the other hand, have special meanings and are used to create more complex patterns.
Here are some examples of metacharacters:
.
(dot): Matches any character except a newline.*
(asterisk): Matches zero or more occurrences of the preceding character or group.+
(plus): Matches one or more occurrences of the preceding character or group.?
(question mark): Matches zero or one occurrence of the preceding character or group.[]
(square brackets): Matches any single character within the brackets.()
(parentheses): Groups multiple characters together.
To write a regular expression in Python, you need to import the re
module. Here is an example that demonstrates the basic syntax:
1import re
2
3# Create a regex pattern
4pattern = r'apple'
5
6# Create a test string
7string = 'I have an apple'
8
9# Use the match() function to check if the pattern exists at the beginning of the string
10match = re.match(pattern, string)
11
12# Check if a match was found
13if match:
14 print('Pattern found!')
15else:
16 print('Pattern not found.')
In this example, the regular expression pattern is 'apple'
, and the test string is 'I have an apple'
. The re.match()
function is used to check if the pattern exists at the beginning of the string. If a match is found, it will print 'Pattern found!'
, otherwise it will print 'Pattern not found.'
.
Remember, regular expressions are case-sensitive by default. To make them case-insensitive, you can use the re.IGNORECASE
flag as an optional argument.
xxxxxxxxxx
import re
# Create a regex pattern
pattern = r'apple'
# Create a test string
text = 'I have an apple'
# Use the match() function to check if the pattern exists at the beginning of the string
match = re.match(pattern, text)
# Check if a match was found
if match:
print('Pattern found!')
else:
print('Pattern not found.')