Can this be done with regex? Find my key in string

Viewed 46

I have regex /[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}/gm to match a key pattern like this AAAAA-AAAAA-AAAAA.

Now I want to modify this regex to match the key pattern in those examples:

"AAAAA-AAAAA-AAAAA",
"dasd:AAAAA-AAAAA-AAAAA.ds",
"AAAAA-AAAAA-AAAAA:dsad",
"das.AAAAA-AAAAA-AAAAA",
"df:AAAAA-AAAAA-AAAAA:das",
"AAAAA-AAAAA-AAAAA asdas",
"dsad adf AAAAA-AAAAA-AAAAA",
"AAAAA-AAAAA-AAAAA adasd asd"

But dont get a match in those examples:

"AAAAA-AAAAA-AAAAA-aaaaaaa",
"sadasAAAAA-AAAAA-AAAAA",
"AAAAA-AAAAA-AAAAAdasd",
"dsa-AAAAA-AAAAA-AAAAA-das",
"adsAAAAA-AAAAA-AAAAAasd"

So the description is: if [a-zA-Z0-9] or - is before or behind a key pattern, I dont want to match it.

I tryed something like that (^[a-zA-Z0-9])?[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}(^[a-zA-Z0-9])? but that didn't work.

Can this be done with just regex or do I need extra code for this?

1 Answers

You can use word boundaries \b on the left and right to prevent a partial match, and at the end of the pattern use a negative lookahead (?!-) to assert not a hyphen directly to the left of the current position.

\b[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}\b(?!-)

Regex demo

const regex = /\b[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}\b(?!-)/;
[
  "AAAAA-AAAAA-AAAAA",
  "dasd:AAAAA-AAAAA-AAAAA.ds",
  "AAAAA-AAAAA-AAAAA:dsad",
  "das.AAAAA-AAAAA-AAAAA",
  "df:AAAAA-AAAAA-AAAAA:das",
  "AAAAA-AAAAA-AAAAA asdas",
  "dsad adf AAAAA-AAAAA-AAAAA",
  "AAAAA-AAAAA-AAAAA adasd asd",
  "AAAAA-AAAAA-AAAAA-aaaaaaa",
  "sadasAAAAA-AAAAA-AAAAA",
  "AAAAA-AAAAA-AAAAAdasd",
  "dsa-AAAAA-AAAAA-AAAAA-das",
  "adsAAAAA-AAAAA-AAAAAasd"
].forEach(s => {
  const match = s.match(regex);
  console.log(match ? `${s} --> ${match[0]}` : `${s} --> No match`);
})

Related