Replace words into a string with a space before or after

Discussion in 'Perl Misc' started by Francesco Moi, Aug 20, 2003.

  1. Hello.

    I've got a string with some words inside, and I'm trying to replace
    'select' to 'choose'.

    $mytext = "select push enter selected";
    $mytext =~ s/select/choose/g;
    print $mytext;

    But sometimes, my string can content 'selected' and it's replace
    to 'choosed'.

    I would like to replace only the words 'select ' or ' selected' (note
    the space after and before 'select'), but I'm not able to find the
    way using regexps.

    Does anybody have any experience? Thank you very much, and best regards.
    Francesco Moi, Aug 20, 2003
    1. Advertisements

  2. Francesco Moi

    Brian Wakem Guest

    The question makes no sense and you contradict yourself, but I think you
    need to be using word boundaries.

    $mytext =~ s/\bselect\b/choose/g;
    Brian Wakem, Aug 20, 2003
    1. Advertisements

  3. Francesco Moi

    PapaBear Guest

    And perhaps, using the same word boundaries, you might consider replacing
    selected by chosen first if you want to maintain proper syntax ;>)

    $mytext =~ s/\bselected\b/chosen/g;

    Never mind the Bear, beware of papa...

    Version: 3.1
    GAT/CS/CM/O d+(--) s++:+>: a? C++(+++)$ UL++(+++) P++>+++ L++>+++ E- W+++$
    N++ !o !K w !O M- V? PS->$ PE+(-) Y+ PGP t+ 5? !X R- tv b+(+++) DI? !D G(-)
    !e h---- r+++ y?
    ------END GEEK CODE BLOCK------
    PapaBear, Aug 20, 2003

  4. So 'preselect ' should become 'prechoose ' ?

    And don't you want ' chosen' rather than ' choose' substituted for that one?

    Use a "word boundary":

    $mytext =~ s/\bselect\b/choose/g;
    $mytext =~ s/\bselected\b/chosen/g;
    Tad McClellan, Aug 20, 2003
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.