-2

My string_first matches with both pattern and pattern_second (see code below). However, I would like for it to be matched only with pattern_second. Could someone help me in achieving this?

import re

string_first = "this-is-first-time"
pattern = "this-is-first"
pattern_second = "this-is-first.*"

if re.search(pattern, string_first):
    print("string match for pattern first")
else:
    print("string not match")

if re.search(pattern_second, string_first):
    print("string match for pattern second")
else:
    print("string not match")
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397

2 Answers2

1

In you pattern specify that you have the end of the line as follows:

pattern = "this-is-first$"

'$' means end of line.

ErikXIII
  • 557
  • 2
  • 11
1

You can try

import re

string_first = "this-is-first-time"
pattern = "this-is-first\s"
pattern_second = "this-is-first.*"

if re.search(pattern, string_first):
    print("string match for pattern first")
else:
    print("string not match")

if re.search(pattern_second, string_first):
    print("string match for pattern second")
else:
    print("string not match")

Output

string not match
string match for pattern second
Leo Arad
  • 4,312
  • 2
  • 4
  • 16