Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Numbers Letters and Hyphens

Last post 11-03-2009, 8:30 PM by Aussie Susan. 1 replies.
Sort Posts: Previous Next
  •  11-03-2009, 5:35 AM 57117

    Numbers Letters and Hyphens

    Hi all, I need a regular expression that allows letters, numbers and hypens only, i.e. 123-ABC. currently my regular expression allows numbers and letters but im having trouble just adding the hyphens which i though was just \-

    My current expression : \w{1, }

     

    many thanks

  •  11-03-2009, 8:30 PM 57129 in reply to 57117

    Re: Numbers Letters and Hyphens

    I would suggest

    [A-Za-z0-9-]+

    Depending on the regex variant you are using (one of the things we ask you to tell us in the Posting Guidelines in the sticky note at the beginning of this forum) the '\w' cal match the underscore as well as the alphanumeric characters. I've also replaced the '{1,}' quantifier with '+' which means the same thing bit I find a bit easier to read.

    If you only want upper- or lower-case characters , then you can remove the other set from the character set definition. Alternatively you can use the "ignore case" option and just use

    [A-Z0-9-]+

    Note that the '-' that represents the hyphen has to be the last character defined in the set otherwise it will be mis-interpreted as the range operator (as it is used between the A and Z etc).

    Also, be aware that your pattern will only tell you that ther eis at least one of the alphanumeric or hyphen characters within the text. Therefore it will match

    %^&(A@#!

    If you are trying to restrict the whole text to be just the characters you are after, then use the pattern

    ^[A-Za-z0-9-]+$

    This forces the match to be from the start of the string ('^') to the end ('$')

    Susan

View as RSS news feed in XML