Mariola has asked for the wisdom of the Perl Monks concerning the following question:

Hello, Amateur in Perl and Programming seeks answer to (I thought until I started searching) simple question: How can I get the code below to accept only one of the titles, and not any other expression or two titles together? At the moment, it accepts any of the listed titles and not any other word, but I won't to avoid it accepting two titles together. How can I program it to accept only one ocurrence of the titles in the list?
# Title, needs to be Dr, Lady, Lord, Miss, Mr, Mrs, Ms or Sir $conditionTitle = 0; do { print("Please enter your title: "); chomp($title = <STDIN>); if($title =~ /^Dr|Lady|Lord|Miss|Mr|Mrs|Ms|Sir|$/) { print("Thank you.\n"); $conditionTitle = 1; } else { print("The allowed titles are: Dr, Lady, Lord, Miss, Mr, Mrs, Ms o +r Sir."); } } while($conditionTitle == 0);

Replies are listed 'Best First'.
Re: Silly question about regular expressions
by Corion (Patriarch) on Jun 23, 2006 at 13:30 UTC

    The regular expression

    /^Dr|Lady|Lord|Miss|Mr|Mrs|Ms|Sir|$/

    matches like the following separated regular expressions:

    /^Dr/ or /Lady/ or ... or /Sir/ or /$/

    ... which, obviously is not what you want. What you want is to group all the alternative titles together and make sure that there is only the title in the string:

    /^(?:Dr|Lady|Lord...|Sir|)$/

    The noncapturing group (?:...) makes sure that the alternatives only extend within it, so the two anchors ^ and $ still anchor the whole string.

      Thanks!
Re: Silly question about regular expressions
by cdarke (Prior) on Jun 23, 2006 at 13:33 UTC
    Try:
    $title =~ /^(Dr|Lady|Lord|Miss|Mr|Mrs|Ms|Sir)$/
    The alternates are now in parentheses, and the placement of the ^ and $ anchors is slightly different.
Re: Silly question about regular expressions
by prasadbabu (Prior) on Jun 23, 2006 at 14:15 UTC

    Hi Mariola

    Corion and cdarke have given good answers for your question.

    In addition, I think you are parsing Names which contains titles.

    You can take a look at Lingua::EN::NameParse which may help you. This module also contains many name titles like yours.

    Prasad