Regex Pros: Please help me solve this little puzzle

Discussion in 'Programming' started by Kellerkind, Feb 9, 2010.

  1. #1
    I have been trying to figure this out for some hours now.... I have to do some regex search and replace in a txt file before I can import it to mysql.

    Here is what I have in the text file:

    hello some random words 55
    anotherhello different number of words and spaces 56
    andanotherhello one word 57

    I need to cut out everything that comes after the first word in a line and before the number in that line and replace it with a comma.

    The final data should look like this:

    hello,55
    anotherhello,56
    andanotherhello,57

    Can any regex pro help me out with this? Would be awesome.
     
    Kellerkind, Feb 9, 2010 IP
  2. krsix

    krsix Peon

    Messages:
    435
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Not really regex, but should work:
    
    <?php
    $filename = 'FILENAME';
    $l = file($filename);
    foreach ($l as $line) {
    $firstword = explode(' ', $line);
    $firstword = $firstword[0];
    preg_match("/(?<=\040)([^\s]+?)$/",trim($line),$lastnumber);
    echo $firstword.','.$lastnumber[0]."\n";
    }
    ?>
    
    PHP:

    my test run:

     
    krsix, Feb 9, 2010 IP
  3. Kellerkind

    Kellerkind Active Member

    Messages:
    160
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    Krsix you rock thank you! If I can't figure the regex out I will do it along with php like you did. Great!

    Anyway I would still love to figure it out as I try to learn more about regex and this is the one I have so far:
    \s(?!\r)(.*?)\s(?=\d)

    The problem here is that it also matches the line breaks.

    *Edit: Got it... finally...
    \s(?<!\n)(.*?)\s(?=\d)
     
    Last edited: Feb 9, 2010
    Kellerkind, Feb 9, 2010 IP