我有一个字符串变量包含
string = "123hello456world789"
Run Code Online (Sandbox Code Playgroud)
字符串不包含空格.我想写一个正则表达式,只打印包含(az)的单词我尝试了一个简单的正则表达式
pat = "([a-z]+){1,}"
match = re.search(r""+pat,word,re.DEBUG)
Run Code Online (Sandbox Code Playgroud)
match对象仅包含单词Hello
且单词World
不匹配.
什么时候使用re.findall()
我可以得到两个Hello
和World
.
我的问题是为什么我们不能这样做re.search()
?
这怎么办re.search()
?
Inb*_*ose 13
re.search()
在字符串中找到一次模式,文档:
扫描字符串,查找正则表达式模式生成匹配项的位置,并返回相应的MatchObject实例.如果字符串中没有位置与模式匹配,则返回None; 请注意,这与在字符串中的某个点找到零长度匹配不同.
为了匹配每一个事件,您需要re.findall()
,文档:
返回字符串中pattern的所有非重叠匹配,作为字符串列表.从左到右扫描字符串,并按找到的顺序返回匹配项.如果模式中存在一个或多个组,则返回组列表; 如果模式有多个组,这将是一个元组列表.结果中包含空匹配,除非它们触及另一个匹配的开头.
例:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
更新:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,您提供的第一个示例失败的原因是因为大写,您可以简单地添加re.IGNORECASE
标志,但您提到匹配应该只是小写.
归档时间: |
|
查看次数: |
49641 次 |
最近记录: |