|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Regular expression (group)
I know in php, you can get multi arrayed results with preg_match and preg_match_all.
I was wondering if that was similar in the group() function in python by creating a list. Example, I have in the text: "mary had a little lamb, and a little rabbit." and I want to search for "little" and it's subsequent word and I want a list of the matches. So I'd have something like this: Code:
content = 'mary had a little lamb, and a little rabbit.' required = '(little\s*?\w*?)\w' p = re.compile(required, re.IGNORECASE) gr = p.search(content) #This is the part I don't know what to do!!! print gr.groups(1) print gr.group(1) I want to create an output that would say: little lamb little rabbit and so on. How would I go about getting that? Thanks Last edited by duniyadnd : April 23rd, 2004 at 02:18 PM. |
|
#2
|
|||
|
|||
|
Quote:
This code: Code:
content = 'mary had a little lamb, and a little rabbit.'
required = 'little\s+\w+(?=\W)'
p = re.compile(required, re.IGNORECASE)
gr = p.finditer(content)
for match in gr:
print match.group(0)
outputs: Code:
little lamb little rabbit |
|
#3
|
|||
|
|||
|
aaaaaah, that worked, thanks.. t
|
|
#4
|
||||
|
||||
|
If you want to get a list instead of an itorator then use the findall() method instead, if you just want to loop over the values finditer() is fine but it lacks the flexability of a list in some respects... IMO of course
![]() Take care guys, Mark. |
|
#5
|
|||
|
|||
|
Quote:
re.finditer is, of course, better not when you want to loop over the actual matches but when you want the actual match objects (with ability to get subgroups, find start and end of matches, etc.) instead of a plain list with text. |
|
#6
|
||||
|
||||
|
Ah, but a list is much easier to manipulate than an itorator! Which is why i find it better since most of the time i'll find myself wanting to do something else with the values
. But for looping i agree with perc of course ![]() Mark. |
|
#7
|
|||
|
|||
|
That discussion helped even more.. Thanks guys..
![]() |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Regular expression (group) |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|