views:

38

answers:

3

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?

A: 

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.

Pablo Santa Cruz
The quantifier `{1}` for any regex atom is redundant.
msw
+2  A: 

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.

eldarerathis
Awesome, thank you.
antimatteraustin
+1  A: 

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"

Dean Harding