Reputation: 2097
I need to validate whether a given string is a valid mDNS address. Examples of these are listed here:
a2aadd61-85d9-4be6-a36c-267ad65917d3.local
ccd58700-cdd5-4c1f-8098-5bc306f1ce77.local
bb4115cd-1f39-42b0-9433-e59533c9c771.local
3b382824-24bf-457a-a7d6-b6e25e4d79bf.local
9284cbaa-2933-45e3-9ae2-c0cccae54b68.local
619281fb-6426-44fa-8d0f-9e58ce415e3e.local
541d8a99-b1a5-46f4-96f1-e31f30b3cb99.local
2feb782f-ea40-4a37-b843-5b5b4fe1860e.local
Is this possible? I am new to regex and can't seem to find any regex examples for this particular string. This was my attempt at making a regex test:
let valid = 'a2aadd61-85d9-4be6-a36c-267ad65917d3.local';
let invalid = 'not-valid-233q4q22eqwr-q3rhHE02n333r4tsefs.local';
let regex = \([a-zA-Z1-9]+){8}-([a-zA-Z1-9]){4}-([a-zA-Z1-9]){4}-([a-zA-Z1-9]){12}\.local\;
regex.test(valid)
Upvotes: 0
Views: 47
Reputation: 13356
First, the regex literal delimiters are not correct. It has to be slash and not backslash.
Second, the +
quantifier of the first character class of exactly eight characters is not needed (even wrong).
Third, the sub-sequence of "4 characters plus dash" appears 3 times in a row. The OP's regex does not reflect this (it covers it just 2 times).
Fourth, in addition to all that, the grouping into parenthesis is of no use. Thus, a regex which fixes and optimizes everything said needs to look close to ... /^[a-z\d]{8}(?:-[a-z\d]{4}){3}-[a-z\d]{12}\.local$/i
.
const regXAddress =
// see ... [https://regex101.com/r/6KWLm9/1]
/^[a-z\d]{8}(?:-[a-z\d]{4}){3}-[a-z\d]{12}\.local$/i;
const testSample =
`a2aadd61-85d9-4be6-a36c-267ad65917d3.local
ccd58700-cdd5-4c1f-8098-5bc306f1ce77.local
bb4115cd-1f39-42b0-9433-e59533c9c771.local
3b382824-24bf-457a-a7d6-b6e25e4d79bf.local
9284cbaa-2933-45e3-9ae2-c0cccae54b68.local
619281fb-6426-44fa-8d0f-9e58ce415e3e.local
541d8a99-b1a5-46f4-96f1-e31f30b3cb99.local
2feb782f-ea40-4a37-b843-5b5b4fe1860e.local
2feb782f-e2a40-4a37-b843-5b5b4fe1860e.local
2feb78f-ea40-4a37-b8432-5b5b4fe1860e.local
2feb78f-ea40-4a37-b8432-5b5b4fe1860.local`;
console.log(
testSample
.split(/\n/)
.map(address =>
`'${ address }' is ${ regXAddress.test(address) ? '' : 'in' }valid`
)
.join('\n')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
Upvotes: 1
Reputation: 33242
I got it to work using this:
let valid = 'a2aadd61-85d9-4be6-a36c-267ad65917d3.local';
let invalid = 'not-valid-233q4q22eqwr-q3rhHE02n333r4tsefs.local';
let regex = /(^[a-zA-Z1-90]{8})-([a-zA-Z1-90]{4})-([a-zA-Z1-90]{4})-([a-zA-Z1-90]{4})-([a-zA-Z1-90]{12})\.local/;
console.log(regex.test(valid)) //=> true
console.log(regex.test(invalid)) //=> false
Posted on behalf of the question asker
Upvotes: -1