gpt4 book ai didi

Python研究

转载 作者:太空狗 更新时间:2023-10-29 17:30:46 24 4
gpt4 key购买 nike

我有一个包含

的字符串变量
string = "123hello456world789"

字符串不包含空格。我想写一个正则表达式,只打印包含(a-z)的单词我尝试了一个简单的正则表达式

pat = "([a-z]+){1,}"
match = re.search(r""+pat,word,re.DEBUG)

匹配对象只包含单词Hello,不匹配单词World

当使用 re.findall() 时,我可以得到 HelloWorld

我的问题是为什么我们不能使用 re.search() 来做到这一点?

如何用 re.search() 做到这一点?

最佳答案

re.search() 在字符串中找到模式一次documenation :

Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

为了匹配每一个的出现,你需要re.findall(), documentation :

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

示例:

>>> import re
>>> regex = re.compile(r'([a-z]+)', re.I)
>>> # using search we only get the first item.
>>> regex.search("123hello456world789").groups()
('hello',)
>>> # using findall we get every item.
>>> regex.findall("123hello456world789")
['hello', 'world']

更新:

由于 your duplicate question ( as discussed at this link ) 我在这里也添加了我的其他答案:

>>> import re
>>> regex = re.compile(r'([a-z][a-z-\']+[a-z])')
>>> regex.findall("HELLO W-O-R-L-D") # this has uppercase
[] # there are no results here, because the string is uppercase
>>> regex.findall("HELLO W-O-R-L-D".lower()) # lets lowercase
['hello', 'w-o-r-l-d'] # now we have results
>>> regex.findall("123hello456world789")
['hello', 'world']

如您所见,您提供的第一个示例失败的原因是大写,您可以简单地添加 re.IGNORECASE 标志,尽管您提到匹配应该是仅限小写。

关于Python研究,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20240239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com