re Insanity

Duncan Booth duncan.booth at invalid.invalid
Sat Jan 22 06:17:09 EST 2005


Tim Daneliuk wrote:

> 
> I tried this:
> 
>      y=re.compile(r'\[PROMPT:.*\]')
> 
> Which works fine when the text is exactly "[PROMPT:whatever]" but
> does not match on:
> 
>     "something [PROMPT:foo] something [PROMPT:bar] something ..."
> 
> The overall goal is to identify the beginning and end of each [PROMPT...]
> string in the line.
> 

The answer sort of depends on exactly what can be in your optional text:

>>> import re
>>> s =  "something [PROMPT:foo] something [PROMPT:bar] something ..."
>>> y=re.compile(r'\[PROMPT:.*\]')
>>> y.findall(s)
['[PROMPT:foo] something [PROMPT:bar]']
>>> y=re.compile(r'\[PROMPT:.*?\]')
>>> y.findall(s)
['[PROMPT:foo]', '[PROMPT:bar]']
>>> y=re.compile(r'\[PROMPT:[^]]*\]')
>>> y.findall(s)
['[PROMPT:foo]', '[PROMPT:bar]']
>>> 

.* will match as long a string as possible.

.*? will match as short a string as possible. By default this won't match 
any newlines.

[^]]* will match as long a string that doesn't contain ']' as possible. 
This will match newlines.



More information about the Python-list mailing list