RegExp Help

J

J. Romano

Indigo5 said:
This may be a simple question, but how would I use a
regular expression to convert reals to integers whenever
possible. For example, if I had the following lines

25.010 36.5 20.00
22.3 19. 35.

I would want those converted to

25.010 36.5 20
22.3 19 35


Try the following two lines together:

s/(\.\d*?)0*(?!\d)/$1/g;
s/\.(?!\d)//g;

The first line looks for a decimal point that's followed by some
digits that are trailed by zeroes. If it finds that pattern, it gets
replaced with the decimal point followed by the digits WITHOUT the
trailing zeroes. (The ?! is a negative look-ahead: it means that the
zeroes have to stop when there is a non-digit right after them
(otherwise, 25.5500001 would get changed to 25.551).) (The *? tells
the * character to be non-greedy. Without the ? the * would "gobble"
up all the digits so that there would be no zeroes left to be gobbled
up by the 0* (and therefore no digits at all would get removed).)

The first line alone does not remove the decimal point if it
appears with no trailing digits (like "19."), so that's why I added
the second line: if there is a decimal point that is not followed by
any digits, remove it.

I hope this helps.

-- Jean-Luc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top