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

Replace capturing group with same amount of a constant character

Last post 11-24-2009, 6:14 PM by StefanL. 0 replies.
Sort Posts: Previous Next
  •  11-24-2009, 6:14 PM 57485

    Replace capturing group with same amount of a constant character

    I was wondering whether it is possible to replace a capturing group with same amount of a constant character (e.g. blanks).
    I stumbled over this question with two tasks lately:

    1. Replacing the first block of blanks in any line of a given file with a block of 'X' of the same length:
      "blabla   blabla blabla      bla" -> "blablaXXXblabla blabla      bla"
      "blablablablabla blabla      bla" -> "blablablablablaXblabla      bla"

      The match is easy (Vim Regex): s/^\([^ ]*\)\(  *\)/\1X/
      But what should go instead of the single 'X' ?

    2. Replace the characters between two specific offsets (n-th and m-th character of a line)  with blanks:
      This can be done easily, but it's annoying to hardcode  (m-n) blanks in the replace-expression.

      Easy but annoying solution: s/^\(.\{50\}\).\{20\}/\1                    /
      Is there a more elegant way to accomplish this?

     As environment any of the *nix-Engines will do. If I have to pick: Vim-Regex or Perl.

    Thanks in advance,
    Stefan

View as RSS news feed in XML