I am trying to match a string if it exactly matches, while ignoring case. Below is the code where my string value is different but still matching.
import re
k = "999"
v = "99"
if (re.search(v, k , re.IGNORECASE)):
print "xyz"
k = "AAA"
v = "aa"
if (re.search(v, k , re.IGNORECASE)):
print "xyz"
In above code k = 999 , v = 99
but matching and k = AAA, v = aa
matching. What I exactly need is if k= 999
and v = 999
then match other all cases should not match. like wise k = AAA
and v = aaA
should match (Meaning ignore case) if k =AAA
and v = aa
should not match.
你的意思是..... if k == v:
不知道为什么要为此使用RegEx,但是无论出于何种原因,ypou都可以使用字符串的开头和字符串的末尾进行匹配。
k = re.compile(r"^99$")
The canonical way to do a case insensitive compare is to use lower()
or upper()
:
Code:
def matches(str1, str2):
return 'matches' if str1.lower() == str2.lower() else 'does not match'
Test Code:
data = (
("999", "99"),
("999", "999"),
("999X", "999x"),
("999Xx", "999x"),
)
def matches(str1, str2):
return 'matches' if str1.lower() == str2.lower() else 'does not match'
for datum in data:
print('%s %s %s' % (datum[0], matches(*datum), datum[1]))
Results:
999 does not match 99
999 matches 999
999X matches 999x
999Xx does not match 999x
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.