To match an exact string using a regular expression (regex), you can use anchors and ensure that the entire string matches your target exactly.
1. Using ^
(start of string) and $
(end of string):
- The
^
anchor asserts that the match occurs at the beginning of the string. - The
$
anchor asserts that the match occurs at the end of the string. - By placing these anchors at both ends of the target string, you can ensure an exact match.
Example:
If you want to match the exact string "Hello"
:
^Hello$
^
ensures that the match starts at the beginning of the string.Hello
is the exact text you want to match.$
ensures that the match ends at the end of the string.
This regex will match strings that are exactly “Hello” and nothing else.
2. Example in Python:
Here’s how you can use this regular expression in Python:
import re
pattern = r"^Hello$"
text = "Hello"
# Check if the text matches the exact string "Hello"
if re.match(pattern, text):
print("Exact match found!")
else:
print("No exact match.")
- In this example,
re.match()
will return a match if the string is exactly"Hello"
. - If
text
is"Hello there"
or"hello"
, it will not match because of the anchors.
3. Other Considerations:
- Ensure that you don’t accidentally allow extra characters before or after the exact string.
- If you’re working with case-insensitive matches, you can use the
i
flag. For example,(?i)^Hello$
will match “hello”, “Hello”, “HELLO”, etc.
Example with Case-Insensitive Matching:
(?i)^hello$
This will match "hello"
, "HELLO"
, "HeLLo"
, etc., regardless of case.