Sunday, 15 April 2012

regex - splitting string in Python (2.7) -



regex - splitting string in Python (2.7) -

i have string such 1 below:

26 (passengers:22 crew:4)

or

32 (passengers:? crew: ?)

. i'm looking split code numbers representing number of passengers , crew extracted. if it's question mark, i'd replaced "".

i'm aware can utilize string.replace("?", "") replace ? how go extracting numeric characters crew or passengers respectively? numbers may vary 2 digits 3 can't piece lastly few characters off string or @ specific interval.

thanks in advance

a regular look match be:

r'\(\s*passengers:\s*(\d{1,3}|\?)\s+ crew:\s*(\d{1,3}|\?)\s*\)'

with whitespace tolerance thrown in.

results:

>>> import re >>> numbers = re.compile(r'\(\s*passengers:\s*(\d{1,3}|\?)\s+ crew:\s*(\d{1,3}|\?)\s*\)') >>> numbers.search('26 (passengers:22 crew:4)').groups() ('22', '4') >>> numbers.search('32 (passengers:? crew: ?)').groups() ('?', '?')

python regex string python-2.7

No comments:

Post a Comment