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


Hi Monks,

I want to match a word with out hyphen's

For example, I able to match the word "hello" by using a-z+.

I don't want to match the word "hello-world", when i am using a-z+

Can any one help me on this...

Thanks in advance

Replies are listed 'Best First'.
Re: hyphen in regular expression
by AnomalousMonk (Archbishop) on Sep 18, 2008 at 13:56 UTC
    A hyphen in a character class [a-d] (and please use <code> ... </code> or <c> ... </c> tags around anything that looks like it might be code, e.g., anything in square brackets) specifies a range of characters; [a-d] is equivalent to [abcd], so you need to use exactly what you used in your original post!

    Note that \w is very close to what you want, except it also includes the underscore character '_' and is affected by locale.

    See: perlre, perlretut, perlrequick.

      It's only affected by locale if use locale; is in effect.
Re: hyphen in regular expression
by ikegami (Patriarch) on Sep 18, 2008 at 15:48 UTC

    Since [a-z]+ doesn't match hyphens, I'm guessing you are doing

    # Matches if the string contains a sequence # of 1 or more lowercase letters $str =~ /[a-z]+/

    when you want to do

    # Matches if the string consists entirely of # a sequence of 1 or more lowercase letters, # optionally followed by a newline $str =~ /^[a-z]+$/

    or

    # Matches if the string consists entirely of # a sequence of 1 or more lowercase letters $str =~ /^[a-z]+\z/
Re: hyphen in regular expression
by toolic (Bishop) on Sep 18, 2008 at 13:51 UTC
    Can any one help me on this...
    ... not very effectively until you provide some more context for your problem:
    • Show a few lines of your actual input data.
    • Show us what you expect your output to look like.
    • Show the code that you have tried.