avaleske
avaleske

Reputation: 1853

Regular expression for a hostname

I'm trying to match a hostname similar to foo-bar3-vm.companyname.local. The part that is foo-bar3 can be any combination of letters, numbers, and hyphens, but I want to ensure it ends in -vm.companyname.local.

I was attempting to use /^[a-zA-Z0-9\-]*[vmVM]*\.companynanme\.local$/, but that seems to match anything ending in .companyname.local.

What's wrong with my regex?

Upvotes: 0

Views: 412

Answers (3)

Dean Harding
Dean Harding

Reputation: 72638

The * means "zero or more times", and [...] means any character from this group. So [vmVM]* means "any of v, m, V or M repeated zero or more times".

What you actually want is:

/^[a-zA-Z0-9\-]*-vm\.companynanme\.local$/i

Note the "i" on the end means "case insensitive"

Upvotes: 1

eldarerathis
eldarerathis

Reputation: 36183

The [vmVM]* portion means match the letters v,m,V, or M zero or more times, so zero repetitions would give you a string ending in just .companyname.local. If you want to be as restrictive as your question makes it sound, just change it to something like:

/^[a-zA-Z0-9\-]*\-[vV][mM]\.companyname\.local$/

Or, if you want at least one letter/number in the hostname, something like:

/^[a-zA-Z0-9][a-zA-Z0-9\-]*\-[vV][mM]\.companyname\.local$/

Edit: Whoops, typo.

Upvotes: 2

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

Try this:

/^[a-zA-Z0-9\-]*[-]{1}[vV]{1}[mM]{1}\.companynanme\.local$/

The {1} quantifier will ensure that you have a hyphen -, one v followed by one m.

The * quantifier means you can have zero or more occurrences of the [] expression. Hence, anything that ends with .companyname.local will match the regular expression posted in your question.

Upvotes: -1

Related Questions