Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

convert ip address to 3 digit octets

Last post 07-07-2009, 6:40 PM by Aussie Susan. 4 replies.
Sort Posts: Previous Next
  •  07-07-2009, 10:05 AM 54857

    convert ip address to 3 digit octets

    if I had a file full of ip address, what would be the best method for converting them to 3 digit octets?

    input:

    1.2.3.4

    22.33.123.234

    output:

    001.002.003.004

    022.033.123.234

  •  07-07-2009, 10:49 AM 54867 in reply to 54857

    Re: convert ip address to 3 digit octets

    TheBigAmbulance:

    if I had a file full of ip address, what would be the best method for converting them to 3 digit octets?

    To code a function to pad the numbers.

    I have no idea of what your question has to do with regular expression though.


    Michael

    "In theory, theory and practice are the same. In practice, they are not."
    Albert Einstein
  •  07-07-2009, 11:08 AM 54871 in reply to 54867

    Re: convert ip address to 3 digit octets

    My thought was to search for the string "fixed" and find the length of the line.  Next, if it is length x instead of length y (full three digit ip address), insert a '0' at the 4th octet.  I can do a simple search/replace for the first 3 octets.  But for the fourth, the x and y length would tell me if the 4th octet was three digits or not.  If it isn't three digits, add a '0' until it matches length y.

    I'm probably making this more complicated than it should be.  I probably need something like left zero padding.

  •  07-07-2009, 11:50 AM 54878 in reply to 54871

    Re: convert ip address to 3 digit octets

    The simplest regex solution would be run mupltiple passes

    1st pass replace all single digit octets with itself and prepend two leading zeros

    2nd pass replace all two digit octets with itself and prepend a leading zero


    Michael

    "In theory, theory and practice are the same. In practice, they are not."
    Albert Einstein
  •  07-07-2009, 6:40 PM 54890 in reply to 54871

    Re: convert ip address to 3 digit octets

    The problem with this approach is that regexs don't have any understanding of the length of captured text. If you had a part of your pattern like

    \.(\d+)\.

    the digits will be captured into the match group but there is no way you can tell how many digits there are within the regex engine itself. All you could do is to have your program get the match group text from the regex engine and manipulate it using the programming languages string functions (or convert it to an integer and then back to a formatted string with the leading zeros added).

    Perhaps because of its history, regex engines are heavily biased towards using a pattern to locate text - the ability to manipulate and replace text extracted using the pattern is very much the poor cousin in this regard.

    Susan 

View as RSS news feed in XML