首页 > 试题广场 >

字符串通配符

[编程题]字符串通配符
  • 热度指数:177383 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}在计算机中,通配符是一种特殊语法,广泛应用于文件搜索、数据库、正则表达式等领域。让我们来学习通配符的匹配规则:
\hspace{23pt}\bullet\,\texttt{`*'} 符号代表匹配 0 个或以上的数字或字母;
\hspace{23pt}\bullet\,\texttt{`?'} 符号代表匹配 1 个数字或字母;
\hspace{23pt}\bullet\,小写字母字符代表匹配自身和自身的大写字母形态;
\hspace{23pt}\bullet\,大写字母字符代表匹配自身和自身的小写字母形态;
\hspace{23pt}\bullet\,其他字符代表匹配自身。

\hspace{15pt}现在,对于给定的通配符字符串 s 和目标字符串 p不考虑大小写,请判断 s 是否可以匹配得到 p。如果可以,输出 \rm true;否则,输出 \rm false

\hspace{15pt}在本题中,给定的字符串由 ASCII 码在 33126 范围内的可见字符构成。您可以参阅下表获得其详细信息(您可能关注的内容是,这其中不包含空格、换行)。
../图片/AllAscii.png

输入描述:
\hspace{15pt}第一行输入一个长度为 1 \leqq {\rm len}(s) \leqq 100、由可见字符构成的通配符字符串 s
\hspace{15pt}第二行输入一个长度为 1 \leqq {\rm len}(p) \leqq 100 、由可见字符构成的目标字符串 p


输出描述:
\hspace{15pt}如果可以匹配得到,输出 \textrm{true};否则,输出 \textrm{false}
示例1

输入

z
zz

输出

false
示例2

输入

Z*
zz

输出

true

说明

\hspace{15pt}在这个样例中,\texttt{`*'} 匹配 \texttt{`z'}。注意,由于不区分大小写,\texttt{`Z'} 可以匹配 \texttt{`z'}
示例3

输入

?*
zz

输出

true

说明

\hspace{15pt}在这个样例中,\texttt{`?'} 匹配 \texttt{`z'}\texttt{`*'} 匹配 \texttt{`z'}
示例4

输入

**Z
0QZz

输出

true

说明

\hspace{15pt}在这个样例中,其中一种匹配方法是:
\hspace{23pt}\bullet\,第一个 \texttt{`*'} 匹配 \texttt{
\hspace{23pt}\bullet\,第二个 \texttt{`*'} 匹配 \texttt{`Z'}
\hspace{23pt}\bullet\,第三个 \texttt{`Z'} 匹配 \texttt{`z'}
示例5

输入

??**
zz

输出

true

说明

\hspace{15pt}\texttt{`*'} 可以匹配 0 个字符。
示例6

输入

HH?*
HH##1

输出

false

说明

\hspace{15pt}可被 \texttt{`*'}\texttt{`?'} 匹配的字符不包含 \texttt{`\#'}
import sys



def is_shuzihuozimu(cha):
    if "0" <= cha <= "9"&nbs***bsp;"a" <= cha <= "z":
        return True
    return False


def str_match(obj_str, reg_str):
    if len(obj_str) != 0 and len(reg_str) == 0:
        return False
    elif len(obj_str) == 0 and len(reg_str) != 0:
        for reg_cha in reg_str:
            if reg_cha != "*":
                return False
        return True
    elif len(obj_str) == 0 and len(reg_str) == 0:
        return True
    else:
        cha = obj_str[0]
        reg_cha = reg_str[0]
        if cha == reg_cha:
            return str_match(obj_str[1:], reg_str[1:])
        else:
            if reg_cha == "?":
                if is_shuzihuozimu(cha):
                    return str_match(obj_str[1:], reg_str[1:])
                else:
                    return False
            if reg_cha == "*":
                if not is_shuzihuozimu(cha):
                    return str_match(obj_str, reg_str[1:])
                else: 
                    return any([str_match(obj_str, reg_str[1:]), str_match(obj_str[1:], reg_str)])
            return False


reg_line = input().lower()
obj_line = input().lower()

if str_match(obj_line, reg_line):
    print('true')
else:
    print('false')
为什么这样还超时啊. 我不理解
发表于 2025-03-05 16:50:40 回复(0)
稀里糊涂做出来了,想问下为啥倒着匹配可以,正着匹配不行?
def foo(s1: str, s2: str) -> bool:
    l1, l2 = len(s1), len(s2)
    if l1 == 0 and l2 == 0:
        return True
    elif l1 == 0:
        return False
    elif l2 == 0:
        if s1 == "*" * l1:
            return True
        else:
            return False
    else:
        p1, p2 = 0, 0
        while p1 < l1 and p2 < l2:
            if s1[p1] == "*":
                if s2[p2].isalnum():
                    return (
                        foo(s1[p1:], s2[p2 + 1 :])
                       &nbs***bsp;foo(s1[p1 + 1 :], s2[p2 + 1 :])
                       &nbs***bsp;foo(s1[p1 + 1 :], s2[p2:])
                    )
                else:
                    p1 += 1
                    continue
            elif s1[p1] == "?":
                if s2[p2].isalnum():
                    p1 += 1
                    p2 += 1
                    continue
                else:
                    return False
            else:
                if s1[p1] == s2[p2]:
                    p1 += 1
                    p2 += 1
                    continue
                else:
                    return False

        if p1 == l1 and p2 < l2:
            return False
        elif p1 < l1 and p2 == l2:
            if len(s1[p1:].replace("*", "")) == 0:
                return True
            else:
                return False
        else:
            return True


a, b = input().lower()[::-1], input().lower()[::-1]
x = "true" if foo(a, b) else "false"
print(x)


发表于 2024-09-25 21:41:11 回复(0)
aa = "0"+input()
bb = "0"+input()
a = []
b = []
for i in range(len(aa)):
    if aa[i].isupper():
        a.append(aa[i].lower())
    else:
        a.append(aa[i])
for j in range(len(bb)):
    if bb[j].isupper():
        b.append(bb[i].lower())
    else:
        b.append(bb[j])

def pd(s):
    if s.islower():
        return True
    elif s.isupper():
        return True
    elif s in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
        return True
    else:
        return False


def qu_xing(lst):
    # 使用列表推导式创建一个新列表,其中不包含'*'元素
    return [item for item in lst if item != "*"]


dp = [["0" for k in range(len(b)+1)] for i in range(len(a)+1)]
dp[0][0] = "1"

# 判断边缘
for i in range(1,len(a)):
    if qu_xing(a[0:i+1]) == ["0"]:
        dp[i][0] = "1"


for i in range(1, len(a)):
    for j in range(1, len(b)):  # 判断a的0~i和b的0~j是否匹配
        if pd(b[j]):
            if a[i] == "*":
                if dp[i-1][j] == "1":
                    dp[i][j] = "1"
                else:
                    dp[i][j] = dp[i][j - 1]
            elif a[i] == "?":
                dp[i][j] = dp[i - 1][j - 1]
            elif a[i] == b[j]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = "0"
        elif a[i] == b[j]:
            dp[i][j] = dp[i - 1][j - 1]
        elif a[i] == "*":
            if dp[i - 1][j] == "1":
                dp[i][j] = "1"
            else:
                dp[i][j] = "0"
        else:
            dp[i][j] = "0"

if dp[len(a) - 1][len(b) - 1] == "1":
    print("true")
else:
    print("false")

发表于 2024-06-19 03:21:27 回复(0)
投机取巧法,重点在于先转换大小写,并且将所有连续的*合并,这样计算较快。
import sys
import re
modStr = input().upper()
mainStr = input().upper()
while modStr.count("**")>0:
    modStr = modStr.replace("**","*")
modStr = modStr.replace("?",r"[A-Z0-9]{1}")
modStr = modStr.replace("*",r"[A-Z0-9]{0,}")
modStr = modStr.replace(".",r"\.")
#print(modStr)
res = re.fullmatch(modStr,mainStr)
if res==None:
    print("false")
else:
    print("true")

mainStr = input().upper()
while modStr.count("**")>0:
    modStr = modStr.replace("**","*")
modStr = modStr.replace("?",r"[A-Z0-9]{1}")
modStr = modStr.replace("*",r"[A-Z0-9]{0,}")
modStr = modStr.replace(".",r"\.")
#print(modStr)
res = re.fullmatch(modStr,mainStr)
if res==None:
    print("false")
else:
    print("true")

发表于 2024-02-14 21:27:27 回复(1)
import sys

a = list(input().lower())
b = list(input().lower())

dp = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)]
dp[0][0] = True
for i in range(1,len(a)+1):
    dp[i][0] = dp[i-1][0] and a[i-1]=='*'
for i in range(1,len(a)+1):
    for j in range(1,len(b)+1):
        dp[0][j] = False
        if a[i-1]!='*':
            if a[i-1]==b[j-1]&nbs***bsp;(a[i-1]=='?' and b[j-1].isalnum()):
                dp[i][j]=dp[i-1][j-1]
        elif a[i-1]=='*':
            dp[i][j]=dp[i-1][j]&nbs***bsp;(b[j-1].isalnum() and dp[i][j-1])
if dp[len(a)][len(b)]:
    print('true')
else:
    print('false')
动态规划~
发表于 2023-04-20 22:26:07 回复(0)
#发现大家和测试用例都有点没考虑到哈,当输入为h*?*和h#a#时,
#返回仍然为true,不合理的,但我也没想到解决办法哈哈哈
def fun(str1, str2):
    if str1 == '' and str2 == '':
        return True
    elif str1 == '' and str2 != '':
        return False
    elif str1 != '' and str2 == '':
        if str1.replace('*', '') == '':
            return True
        else:
            return False
    else:
        m, n = len(str1), len(str2)
        if str1[m-1] == str2[n-1]&nbs***bsp;(str1[m-1] == '?' and str2[n-1].isalnum()):
            return fun(str1[:m-1], str2[:n-1])
        elif str1[m-1] == '*':
            return fun(str1[:m-1], str2)&nbs***bsp;fun(str1, str2[:n-1])
        else:
            return False

while True:
    try:
        str1, str2 = input().lower(), input().lower()
        if fun(str1, str2):
            print('true')
        else:
            print('false')
        
    except:
        break

发表于 2023-03-01 17:37:58 回复(0)
import re
regx, s = input().lower(), input().lower()
regx = regx.replace('.', '\.').replace('*','\w*').replace('?', '\w{1}')
c = re.findall(regx, s)
print('true' if s in c else 'false')

发表于 2022-11-23 21:19:56 回复(0)
#思路:直接用正则的fullmatch匹配
#不行
    #一是由于这里要求*?能直接匹配字符,而正则中是匹配前一项字符
    #二是?在正则中匹配一次或0次,这里只能匹配一次
    #三是用fullmatch匹配的话,会超时。可以用match匹配,看结果是否一致
#解决方法:将?替换为\w{1},将*替换为\w{0,},用match匹配,进行比较


import re
model=input().replace('?','\w{1}').replace('*', '\w{0,}')
text=input()

flag=re.match(model,text,re.I)

if flag==None&nbs***bsp;flag.group()!=text:
    print('false')
else:
    print('true')

发表于 2022-05-06 00:03:29 回复(2)
import re
while True:
    try:
        a = input()
        b = input()
        a = a.lower()
        b = b.lower()
        a = a.replace('?','[0-9a-z]{1}').replace('*','[0-9a-z]*').replace('.','\.')  #通配符变成正则表达
        c = re.findall(a,b)
        if(b in c):
            print('true')
        else:
            print('false')
    except:
        break

发表于 2022-04-06 14:46:43 回复(2)
import re
while True:
    try:
        r = input().replace('?', '\w{1}').replace('*', '\w{0,}')
        s = input()
        res = re.findall(r'{}'.format(r), s, re.IGNORECASE)
        # # 确保匹配的值和目标值相同
        print('true') if res != [] and (res[0] == s) else print('false')
    except:
        break
发表于 2022-03-06 11:45:42 回复(0)
import re
while True:
    try:
        string1 = input().lower()
        string2 = input().lower()
        string1 = string1.replace('?', '[a-z0-9]').replace('.', '\.').replace('*', '[0-9a-z]*')
        stringRegex = re.compile(string1)
        if stringRegex.search(string2) and string2 == stringRegex.search(string2).group():
            print('true')
        else:
            print('false')
    except:
        break

发表于 2022-02-01 22:23:06 回复(1)

def func(s1,s2):
    for j1 in s2:
        if (ord(j1)>=97 and ord(j1)<=122) or ord(j1)==63 or ord(j1)==42 or ord(j1)==46 or (ord(j1)>=48 and ord(j1)<=57):
            pass
        else:
            return 'false'
    if ('?' not in s1) and ('*' not in s1):
        if s1 != s2:
            return 'false'
        else:
            return 'true'
    else:
        s=''
        flag=0
        for j in range(len(s1)):
            i=s1[j]
            if flag==0:
                if i!='?' and i!='*':
                    s+=i
                else:
                    flag=1
                    s=''
                if s not in s2:
                    return 'false'
                else:
                    pass
            else:
                if i!='?' and i!='*':
                    s+=i
                else:
                    flag=0
                    s=''
                if s not in s2:
                    return 'false'
                else:
                    pass
            #x=s1.index(i)
            y=len(s1)-1
            if j==y and s!='':
                if s!=s2[-len(s):]:
                    return 'false'
    return 'true'


while True:
    try:
        s1=input().strip().lower()
        s2=input().strip().lower()
        print(func(s1,s2))
    except:
        break
发表于 2021-07-14 13:53:20 回复(1)