有没有一种方法可以用“find”函数实现通配符方法?

2024-05-19 09:48:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python很陌生。我知道find函数接受一个字符串p和一个子字符串s,并返回s在p中出现的索引

p = 'abc'
text = 'aaaabbaac'
text.find(p)

是否可以编写一个方法,允许我将通配符设置为b,并且仍然返回a和c匹配的索引,而不是返回-1?在

我在一个有两个方法的类中使用这个方法,find方法和一个“setwildcard”方法,它接受一个字符并执行我上面描述的操作。默认情况下,通配符设置为“无”。在


Tags: 方法函数字符串text情况find字符abc
1条回答
网友
1楼 · 发布于 2024-05-19 09:48:32

您可以compile将正则表达式模式转换为正则表达式对象,该对象可用于使用其match()search()方法进行匹配。在

import re 
reObj2 = re.compile(pattern)  
reObj2.search(s)  

re.match() will only match at the beginning of the string and not at the beginning of each line.

re.search() scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance.

另外,如果要返回字符串中模式的所有非重叠匹配,可以使用re.findall()。在

看看re。在

希望这有帮助。在

相关问题 更多 >

    热门问题