in reply to Using pos() inside regexp

s/([^\n]{0,14},|[^\n]{15})(?=[^\n])/$1\n/g

- tye        

Replies are listed 'Best First'.
Re^2: Using pos() inside regexp (no /e)
by braveghost (Acolyte) on Oct 08, 2010 at 10:45 UTC
    Ups, your solution is much better than mine, thanks a large. There is a small problem with last line in that case so i think better to use something like
    s/((?:[^\n]{0,15}$)|(?:[^\n]{0,14},)|(?:[^\n]{15})(?=[^\n]))/$1\n/g;
    nevertheless it's interesting to know is it possible to use pos() function to set search position inside of regexp, or it works outside only.
      If I'm reading that correctly, you want a newline at the end? If so, the following will do:
      # Adds trailing newline s/([^\n]{0,14},|[^\n]{15})(?!\n)/$1\n/g
      Compare with tye's:
      # Doesn't add trailing newline s/([^\n]{0,14},|[^\n]{15})(?=[^\n])/$1\n/g

        Did you try your solution? It doesn't add a trailing newline (nor fix the more important problem). Here's my next stab:

        s{( (?:[^\n]{1,15})(?=\n|$) # Line requiring no wrapping | (?:[^\n]{0,14},)(?!\n) # Line that can be wrapped at comma | (?:[^\n]{15})(?!\n) # Line to be wrapped, not at comma )\n? }{$1\n}gx;

        And just two test cases:

        (update) Note there are three ways to write part of that: (?=\n|$) or (?![^\n]) or (?m:$). The last can be written as just $ by putting the m option on the end of the s/// construct. I leave the choice up to you.

        - tye        

      No. The pos() works only outside of matching. It works with the position where the matching operation has stopped. During matching this function does not make sense. \G references the position from the previous matching.

        The pos() works only outside of matching.

        Except when it works inside of matching ;)

        $ perl -le'() = "abcdef" =~ /..(?{ print pos() })/g;' 2 4 6
        hmm i can read pos() value during matching, so why can't i set it? Sence of this action is deep control of regexp actions.
        And about \G, i have no idea how can \G assertion help me to make work regexp from first post:
        $data =~s/([^\n]{16})/ch($1)/ge;
        Could you, explain how it can help me?