REGEX - For Alphanumeric/numeric with potential slash in between

Viewed 100

I am trying to extract a alphanumeric value from a string array using RegEx. Examples:

  1. Apartment 101/B First
  2. Villa 3324/A Second
  3. Milk 12MG/ML Third
  4. Sodium 0.00205MG/ML Fourth
  5. Water 0.00205MG Fifth
  6. Eggs 100 Sixth

My aim is to extract values: 101/B, 3324/A, 12MG/ML, 0.00205MG/ML from the above string arrays. The RegEx I was able to get is something like this: ^[a-zA-Z0-9\.]*$ which is generic alphanumeric regex.

1 Answers

You can match digits followed by optional chars A-Z and then / and uppercase chars

\b\d+(?:\.\d+)?[A-Z]*\/[A-Z]+\b
  • \b A word boundary to prevent a partial match
  • \d+(?:\.\d+)? Match 1+ digits with an optional decimal part
  • [A-Z]* Match optional chars A-Z
  • \/[A-Z]+ Match / and 1+ chars A-Z -\b A word boundary

Regex demo

const regex = /\b\d+(?:\.\d+)?[A-Z]*\/[A-Z]+\b/;
[
  "Apartment 101/B First",
  "Villa 3324/A Second",
  "Milk 12MG/ML Third",
  "Sodium 0.00205MG/ML Fourth",
].forEach(s => {
  const m = s.match(regex);
  if (m) {
    console.log(m[0]);
  }
});


Edit

For matching an optional forward slash and also only digit, you can make the part of the pattern optional.

\b\d+(?:\.\d+)?[A-Z]*(?:\/[A-Z]+)?\b
  • \b A word boundary
  • \d+(?:\.\d+)? Match 1+ digits with an optional part
  • [A-Z]* Match optional uppercase chars A-Z
  • (?:\/[A-Z]+)? Optionally match / and 1+ uppercase chars A-Z
  • \b A word boundary

Regex demo

Related