My code can work in this situation:
import re
strA = "1999年9月9日"
strB = "1999年"
strC = "999年"
print(re.match(strB, strA))
print(re.match(strC, strA))
For example, strB is in the head of strA, return True, while strC is not in the head of strA, even though strA contains strC.
Now, the problem is when there are some parentheses () in strings,like
strA = "(1999年)9月9日"
strB = "(1999年)"
it cannot work in regex ,I know it is on escape character, but how to solve this problem, I mean I cannot modifiy every string to strB = "\(1999年\)"
,or other solutions?
CodePudding user response:
You can use startswith()
. There is no need to use regex.
import re
strA = "1999年9月9日"
strB = "1999年"
strC = "a1999年"
print(strA.startswith(strB)) # = True
print(strA.startswith(strC)) # = False
CodePudding user response:
Use the regex pattern ^1999年
:
# -*- coding: utf-8 -*-
import re
inp = ["1999年9月9日", "a1999年"]
for i in inp:
if re.search(r'^1999年', i):
print("MATCH: " i)
else:
print("NO MATCH: " i)
This prints:
MATCH: 1999年9月9日
NO MATCH: a1999年