in reply to Beginner question about search and replace

As moritz explained you were matching every pair of numbers when you wanted every number with a space following it.

Another way to replace every space following a number with a semicolon could be *(untested):

  s/(\d)(?:\s+)/$1;/g

The \d matches any single digit and is the same as [0-9]. As you learned in your attempt, the parentheses 'capture' that match and store it in memory so we can use it later. The second part of our match looks for at least one space following that digit but doesn't store it in memory because of the (?: ) since we're not planning on using it to help build our replace pattern.

Aside from the perldocs on regexes, if you're interested, you might like Mastering Regular Expressions by Jeffrey E.F. Friedl and/or Data Munging with Perl by Dave Cross.

UPDATE
Same day, 16.Sep.2011 :: 02:35:24 PM :: Changed: s/(\d)(?:\s)+/$1;/g   To : s/(\d)(?:\s+)/$1;/g   Following AnomalousMonk's suggestion.


"...the adversities born of well-placed thoughts should be considered mercies rather than misfortunes." — Don Quixote

Replies are listed 'Best First'.
Re^2: Beginner question about search and replace
by Kc12349 (Monk) on Sep 16, 2011 at 15:32 UTC

    Why the (?: ) around the space character? It runs just fine as below.

    s/(\d)\s+/$1;/g;

      "Why the (?: ) around the space character? It runs just fine as below?"

      It does work well and is less complex to explain. I use the (?: ) to show the practice of not capturing matches into memory which wont be used in the replacement. In this specific example memory isn't going to be a problem because we're only dealing with a single string. But I personally like using it even as a way to mark what I want and don't want to work with in the replacement.

      "...the adversities born of well-placed thoughts should be considered mercies rather than misfortunes." — Don Quixote

        Fair enough. I was just curious if I was missing something. Thanks

      I agree with luis.roca's use of  (?:\s)+ in a pedagogic or self-documentary context as already explained above.

      I would be inclined to quibble with the use of  (?:\s)+ versus  (?:\s+) especially in a pedogogic example. While these two expressions behave in exactly the same way in all respects AFAIU, the corresponding capturing expressions  (\s)+ and  (\s+) behave very differently as to the characters captured, and in an explanatory example this might, by suggestion or implication, lead to great confusion.