Please help with regular expression finding multiple floats
bytecolor at gmail.com
Fri Oct 23 11:48:45 CEST 2009
On Oct 22, 3:26 pm, Jeremy <jlcon... at gmail.com> wrote:
> My question is, how can I use regular expressions to find two OR three
> or even an arbitrary number of floats without repeating %s? Is this
Any time you have tabular data such as your example, split() is
generally the first choice. But since you asked, and I like fscking
with regular expressions...
# I modified your data set just a bit to show that it will
# match zero or more space separated real numbers.
1.0000E-08 1.58024E-06 0.0048 1.0000E-08 1.58024E-06
ntuple = re.compile
# match beginning of line (re.M in the
# chew up anything before the first real (non-greedy -
# named match (turn the match into a named atom while allowing
# match one
# followed by zero or more space separated
# match end of line (re.M in the
""", re.X | re.M) # re.X to allow comments and arbitrary
for mo in re.finditer(ntuple, data)]
Now compare the previous post using split with this one. Even with the
comments in the re, it's still a bit difficult to read. Regular
are brittle. My code works fine for the data above but if you change
structure the re will probably fail. At that point, you have to fiddle
the re to get it back on course.
Don't get me wrong, regular expressions are hella fun to play with.
to ask yourself, "Do I really _need_ to use a regular expression here?"
More information about the Python-list