Regular expressions - For alphanumeric or numeric with a possible slash character included

I need assistance with extracting alphanumeric values from a string array using RegEx. For instance:

  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 goal is to retrieve the values: 101/B, 3324/A, 12MG/ML, 0.00205MG/ML from the provided string arrays. The RegEx pattern I currently have is: ^[a-zA-Z0-9\.]*$, which is a generic alphanumeric regex.

Answer №1

To find digits followed by optional uppercase letters, a forward slash, and more uppercase letters, use this regex pattern:

\b\d+(?:\.\d+)?[A-Z]*\/[A-Z]+\b
  • \b This signifies a word boundary to prevent partial matches
  • \d+(?:\.\d+)? Matches one or more digits with an optional decimal part
  • [A-Z]* Matches any number of optional uppercase letters
  • \/[A-Z]+ Matches a forward slash followed by one or more uppercase letters -\b Another word boundary

Check out the Regex demo here

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

If you want to make the forward slash optional and only match digits, modify the pattern like this:

\b\d+(?:\.\d+)?[A-Z]*(?:\/[A-Z]+)?\b
  • \b Signifies a word boundary
  • \d+(?:\.\d+)? Matches one or more digits with an optional part
  • [A-Z]* Matches any optional uppercase letters A-Z
  • (?:\/[A-Z]+)? Optionally matches a forward slash and one or more uppercase letters A-Z
  • \b Another word boundary

View the updated Regex demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for sending data to a database using a URL?

I am in need of developing a public API for my application that will be capable of receiving a single POST request. The main goal is to provide users with the ability to submit data directly to my database without having to manually interact with forms on ...

The correct way to extract a jwt token from headers and integrate it into an express application

After successfully implementing both the frontend and backend in express.js with authentication and authorization using JWT, I have confirmed that the JWT token is being properly set upon login. You can see the auth-token key in the image below: https://i ...

How can we transform words with double "OO" in a paragraph into green squares using React? For instance, changing "clooney" to "cl[green square]ey"

import React, { Component } from 'react'; class App extends Component { constructor() { super(); this.state = { modifiedPar: "", newPar: "modified paragraph will be displayed here"}; } greenSquareMaker = word = ...

What is the best way to retrieve an ID when parsing JSON recursively?

Could you provide guidance on how to retrieve the IDs of all children when parsing JSON data? I have attempted to use a recursive function, but it seems to be calling infinitely. For reference, here is my code snippet: http://jsfiddle.net/Ds8vQ/ for(var ...

``There seems to be an issue with setting the input value attribute using jQuery's .html

I've been trying to update the value attribute in the input element within my HTML code, but so far, I haven't had any luck with it. HTML: <div class='photo-info'> Photo Name : <span class='photo-name'><?p ...

Issues arise with controlling access due to cache-control and canvas properties

I am attempting to utilize the browser canvas feature to manipulate images that are hosted on cloudfront. My goal is to configure cloudfront in a way that allows the browser to cache images with cache control set to max-age, while still enabling canvas edi ...

Steps for importing a React component as an embedded SVG image

I have developed a SVG component in React by converting an SVG file to a React component using the svg-to-react cli tool. In order to load and display additional svg files within this component, I am utilizing the SVG image tag as demonstrated below. This ...

Altering the playback of a flash object using HTML or JavaScript

Can the playback speed of a flash object be adjusted without recompiling the object, like through HTML attributes or JavaScript? Appreciate any help in advance ...

Switching from jQuery to vanilla JavaScript, iterating through each HTML tag in a loop

Here is my current jQuery code that I am looking to convert into vanilla JavaScript. var elements = []; document.querySelectorAll('*:not(script, style, iframe)').forEach(function(element) { elements.push(element); }); I have tried using d ...

The parameters remain consistent across all Angular directives

I have created a directive called 'filterComponent' with the following code: app.directive('filterComponent', function() { return { restrict: 'E', templateUrl: 'filter-component.html', link: function ...

The error message "mapboxgl is not defined" indicates that the mapboxgl variable

I have been encountering the following error message in the console, and despite spending hours trying to troubleshoot it, I have been unsuccessful in resolving the issue. Could someone assist me in fixing this problem? error image I am having difficulty ...

Enhancing TypeScript with Generic Proxyify Functionality

I'm attempting to enclose a basic interface provided through a type generic in order to alter the return value of each function within the interface. For instance: interface IBaseInterface { test(a?: boolean, b?: number): Promise<boolean>; ...

Guide on how to send files to an API using a form in React with MUI

I am struggling with sending an image through the front-end to my back-end application that is set up to accept data. Here is the code I have: import { useState } from 'react'; import axios from '../../config'; import { useNavigate } fr ...

Why are the elements not found by their id when I check them, even though they were created dynamically using an ajax-generated form with php-inserted values through a

How can I prepopulate form fields displayed in a modal view using jQuery after retrieving the form HTML with an AJAX query? I am trying to set the values through a JavaScript function that retrieves PHP-generated values via document.getElementById. However ...

click event on ion card

Attempting to handle a click event within an ion-card using Ionic 5.0.2 version has presented some challenges. Despite my efforts, I have not been successful in handling the event with the expected function. Here is a snippet of my code: Dynamic card list ...

Use regular expressions to locate all closing HTML tags and all opening HTML tags individually

My JavaScript function is currently filtering strings by removing all HTML tags. However, I have now realized that I need to perform two separate operations: first, replacing all closing tags with <br>, and then removing all opening tags. return Str ...

The state variable is not accurately captured as it passes through various components

For the sake of readability, I have omitted certain sections of my original code. Apologies if this leads to any confusion! In App.js, there is a state variable defined as follows: const [tasks, setTasks] = useState([]) From App.js, the state varia ...

Angular.js: The $setDirty() method on a form does not automatically affect its child form elements

Currently, I am working on a form validation project using Angular.js. A specific challenge that I am facing is setting the dirty state on a child element of a form in an isolated scope within a directive. Does anyone know how to achieve this and set the i ...

Managing iframe scrolling using the parent window's scrollbar

I am currently working on an iframe to be utilized across various domains. The functionality of this iframe involves displaying a data list that updates when the bottom of the scroll is reached. An issue I encountered is that the parent window, where the ...

Storing dates as collection names is not supported in Firestore

I'm currently facing an issue trying to store stock prices in Firestore. I want the structure to resemble something similar to SQL, like this: const d1 = new Date(); const result = d1.getTime(); console.log('Epochtime',result); database.coll ...