none
Regexp pattern to add ".0" to integers

    Question

  • I am trying to write a pattern to search and replace any pure integers in an expression with decimal numbers by adding ".0" at the end of them. For example, "1 / 2" should be changed to "1.0 / 2.0". However, any existing decimals need to be left alone, for example "1.0 / 2" should come out as "1.0 / 2.0". I'm trying various patterns involving (\d+) and [^\.], but having trouble getting it exactly right.

    If this seems a strange thing to want to do (I've done some searching and haven't found anyone else asking about it), here's the larger context. I ultimately want to use a SQL Server stored procedure as an expression evaluator, so I could say EXEC evaluate '2+2', @outputParam and have it return 4 in @outputParam. I've got that part working fine, except for the SQL Server rule that results are returned in the highest precision type of any of its inputs. This is a problem in the case of division: Passing "1/2" or even "2/3", for example, returns 0, because both arguments are integers, therefore the result is an integer with the remainder truncated. (Try "SELECT 1/2" into a query tool and you'll see this.) So my thought is to add ".0" to all integers in the expression, to force the return value to be decimal. And it works, but ideally I don't want the end user to have to remember that, so I'd like the code to do it automatically.

    Any ideas? Thanks in advance.


    UPDATE: Lower priority now, because I just wrote a Transact-SQL function to do the replacing using PATINDEX and normal string processing. But a .Net RegExp solution would have been so many fewer lines of code. :-)
    • Edited by JohnBrooking4 Wednesday, January 25, 2017 5:44 PM Added update
    Wednesday, January 25, 2017 4:27 PM

Answers

  • Check this example:

    string example = "12/34.5 + 67 - 89E10";
    string result = Regex.Replace( example, @"(?<![.]|(e|E)(\+|-)?|\d)(?<number>\d+)(?![.]|\d)", "${number}.0" );
    Console.WriteLine( result );



    • Edited by Viorel_MVP Wednesday, January 25, 2017 6:24 PM
    • Proposed as answer by Kristin Xie Thursday, January 26, 2017 2:18 AM
    • Marked as answer by JohnBrooking4 Thursday, January 26, 2017 2:00 PM
    Wednesday, January 25, 2017 6:23 PM

All replies

  • Check this example:

    string example = "12/34.5 + 67 - 89E10";
    string result = Regex.Replace( example, @"(?<![.]|(e|E)(\+|-)?|\d)(?<number>\d+)(?![.]|\d)", "${number}.0" );
    Console.WriteLine( result );



    • Edited by Viorel_MVP Wednesday, January 25, 2017 6:24 PM
    • Proposed as answer by Kristin Xie Thursday, January 26, 2017 2:18 AM
    • Marked as answer by JohnBrooking4 Thursday, January 26, 2017 2:00 PM
    Wednesday, January 25, 2017 6:23 PM
  • That appears to work! Thank you! You are a RegExp god! :-)
    Wednesday, January 25, 2017 6:55 PM