Tuesday, January 21, 2025
HomeProgrammingRegular Expression For Exact Match Of A String - Regex

Regular Expression For Exact Match Of A String – Regex

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.
See also  What Is Variable In Programming?

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.
See also  What is Tag in HTML?

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.
See also  How to Loop Through an Array in jQuery: A Guide for JavaScript Developers

Example with Case-Insensitive Matching:

(?i)^hello$

This will match "hello", "HELLO", "HeLLo", etc., regardless of case.

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x