Skip to main content
 首页 » 编程设计

python之匹配多个单词正则表达式,python

2024年08月27日32kevingrace

我需要从一个字符串中匹配一个模式。字符串是可变的,所以我需要在其中开发一些可变性。
我需要做的是提取与“布局”一起出现的单词,它们以 4 种不同的方式出现

1 word -- layout` eg: hsr layout 
 
2words -- layout eg: golden garden layout 
 
digit-word -- layout eg: 19th layout 
 
digit-word word --layout eg:- 20th garden layout 

可以看出,我需要数字字段是可选的。一个正则表达式必须做到这一点。这是我所做的:

import re 
p = re.compile(r'(?:\d*)?\w+\s(?:\d*)?\w+l[ayout]*') 
text = "opp when the 19th hsr layut towards" 
q = re.findall(p,text) 

在这个表达式中我需要 19th hsr 布局。但是上面的代码没有返回。我上面的代码有什么问题?

一些字符串示例是:

str1 = " 25/4 16th june road ,watertank layout ,blr"  #extract watertank layout  
str2 = " jacob circle 16th rusthumbagh layout , 5th cross" #extract 16th rustumbagh layout 
str3 = " oberoi splendor garden blossoms layout , 5th main road"  #extract garden blossoms layout 
str4 = " belvedia heights , 15th layout near Jaffrey gym" #extract 15th layout 

请您参考如下方法:

按照我的评论使用 r'(?:\w+\s+){1,2}layout':

>>> import re 
>>> p = re.compile(r'(?:\w+\s+){1,2}layout') 
>>> p.findall(" 25/4 16th june road ,watertank layout ,blr") 
['watertank layout'] 
>>> p.findall(" jacob circle 16th rusthumbagh layout , 5th cross") 
['16th rusthumbagh layout'] 
>>> p.findall(" oberoi splendor garden blossoms layout , 5th main road") 
['garden blossoms layout'] 
>>> p.findall(" belvedia heights , 15th layout near Jaffrey gym") 
['15th layout'] 

{1,2} 用于匹配最多 2 个单词。