Larry Cai
Larry Cai

Reputation: 59933

regular expression for matching

It is for a normal register name, could be 1-n characters with a-zA-Z and -, like

larry-cai, larrycai, larry-c-cai, l,

but - can't be the first and end character, like

-larry, larry-

my thinking is like

^[a-zA-Z]+[a-zA-Z-]*[a-zA-Z]+$

but the length should be 2 if my regex

should be simple, but don't how to do it

Will be nice if you can write it and pass http://tools.netshiftmedia.com/regexlibrary/

Upvotes: 2

Views: 179

Answers (6)

Sector
Sector

Reputation: 1210

maybe this?

^[^-]\S*[^-]$|^[^-]{1}$

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

A simple answer would be:

^(([a-zA-Z])|([a-zA-Z][a-zA-Z-]*[a-zA-Z]))$

This matches either a string with length 1 and characters a-zA-Z or it matches an improved version of your original expression which is fine for strings with length greater than 1.

Credit for the improvement goes to Tim and ridgerunner (see comments).

Upvotes: 4

rubyprince
rubyprince

Reputation: 17793

Try this:

^[a-zA-Z]+([-]*[a-zA-Z])*$

Upvotes: 1

chriso
chriso

Reputation: 2552

Not sure which lazy group takes precedence..

^[a-zA-Z][a-zA-Z-]*?[a-zA-Z]?$

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

You didn't specify which regex engine you're using. One way would be (if your engine supports lookaround):

^(?!-)[A-Za-z-]+(?<!-)$

Explanation:

^           # Start of string  
(?!-)       # Assert that the first character isn't a dash
[A-Za-z-]+  # Match one or more "allowed" characters
(?<!-)      # Assert that the previous character isn't a dash...
$           # ...at the end of the string.

If lookbehind is not available (for example in JavaScript):

^(?!-)[A-Za-z-]*[A-Za-z]$

Explanation:

^           # Start of string  
(?!-)       # Assert that the first character isn't a dash
[A-Za-z-]*  # Match zero or more "allowed" characters
[A-Za-z]    # Match exactly one "allowed" character except dash
$           # End of string

Upvotes: 6

Gumbo
Gumbo

Reputation: 655189

This should do it:

^[a-zA-Z]+(-[a-zA-Z]+)*$

With this there need to be one or more alphabetic characters at the begin (^[a-zA-Z]+). And if there is a - following, it needs to be followed by at least one alphabetic character (-[a-zA-Z]+). That pattern can be repeated arbitrary times until the end of the string is reached.

Upvotes: 4

Related Questions