擅长:python、mysql、java
<p>这可以用<a href="http://pyparsing.wikispaces.com/Examples" rel="nofollow">Pyparsing</a>这样的工具来完成(相当优雅):</p>
<pre><code>from pyparsing import Group, Literal, Optional, Word
import string
code = Group(Optional(Literal("c"), default='') + Word(string.digits) + Optional(Literal(","), default=''))
parser = Literal("start:") + OneOrMore(code) + Literal(";")
# Read lines from file:
with open('lines.txt', 'r') as f:
for line in f:
try:
result = parser.parseString(line)
codes = [c[1] for c in result[1:-1]]
# Do something with teh codez...
except ParseException exc:
# Oh noes: string doesn't match!
continue
</code></pre>
<p>比正则表达式更干净,返回代码列表(不需要<code>string.split</code>),并忽略行中的任何额外字符,就像您的示例一样。</p>