Thursday 15 July 2010

python - What should I use the Non-greedy match in this case -


Assume that I have a string that contains some data fields, which are "|" Are different from, like 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |

My objective is to get the eighth area, this is what I am doing:

  pattern = re.compile (r '^ \ s + (\ | *. *? \ |) {8} ') match = pattern.match (test_line) match: print: match.group (8)   

but it seems that it can not match . I know in this case that I have to use it? For a non-greedy match, but why did not I get the 8th field?

Thanks

Regex can complicate this problem, to simplify it Instead, an easy way to get an eighth object is using the delimited string split () :

  a = '| Here | Is | Some | Data | Different | By | Bar Hooray! | ' Print a.split ('|') [8]   

returns

  hooray!   

Use regex , there will be a way to get it:

  import re a = '| Here | Is | Some | Data | Different | By | Bars | Hooray |! 'Pattern = recompile (r' ([^ \ |] +) 'match = pattern.fundall (a) print match [7]   

returns

  Hooray!    

No comments:

Post a Comment