You said:

G and Y in the example could be any chars.

Well, in case your code is still not doing exactly what you want, and you're still wondering how to fix it, maybe it's time to provide some of the real examples that you are actually dealing with.

I have to say that the example string in the OP is probably not what you meant it to be. In this statement:

$second_str = "591[\s-~]*G-Y[\s-~]*6";
the value assigned to "$second_str" is actually:
591[s-~]*G-Y[s-~]*6
Do you really have literal strings in your data that look like that? If you really do, is there some special rule about hyphens that are inside square brackets (don't replace with space) vs. hyphens that are not inside square brackets (replace these with space)?

If it's just a matter of replacing all hyphens with spaces, then this will do it more efficiently:

tr/-/ /;
But if you have contextual constraints (e.g. must be adjacent to letters/alphanumerics, and/or must not be within bracketed strings, or whatever), you haven't really given us any clear idea about that yet.

In reply to Re^2: Replace not working by graff
in thread Replace not working by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.