The quickest regular expression match possible if it is already a subsection of another match

Is there a simple way to find the shortest match in a long text where strings are repeated? I'm having trouble because matches within already matched text aren't being found.

Here's an example of the issue:

  • Using code: "ababc".match(/a.+c/g)
  • Resulting in: ["ababc"]
  • Expected outcome: ["ababc", "abc"]

I am looking for a solution that doesn't involve manually writing recursive code to search within matches. Any ideas?

Answer №1

Like I mentioned earlier, using just regex won't achieve what you're trying to do.

You presented a basic example, so it's hard to say how useful this will be for your specific case. However, here is my attempt at addressing your needs. It seems like the characters "a" and "c" may vary, so you might have to adjust the code accordingly (e.g. pass them as arguments).

function findShortestMatch(str) {
  var str = str || '';
  var match,
    index,
    regex,
    length,
    results = [];
  
  for (index = 0, length = str.length; index < length; index++) {
    if (str[index] === 'a') {
      regex = new RegExp('^.{' + index + '}(a.+?c)');
      match = str.match(regex);
      
      if (match && match[1]) {
        results.push(match[1]);
      }
    }
  }

  results.sort(function(a, b){
    return a.length - b.length;
  });

  console.log(results);

  return results[0];
}

Example

findShortestMatch('ababcabbc');

// output of all matches found 
["abc", "abbc", "ababc"]

// result
"abc"

Note: This function prioritizes finding the shortest match between an 'a' and a 'c', rather than all possible matches. If you need all matches, including longer ones, consider using a greedy regex with .+.

Answer №2

Iterate through each substring by starting from every character onwards (using the slice method), check for a match against a regular expression anchored to the beginning of the string (^), and employ non-greedy matching (?):

const input = "ababc";
const regexp = /^a.+?c/;

const results = [];
    
for (let i = 0; i < input.length; i++) {
  let match = input.slice(i).match(regexp);
  if (match) results.push(match[0]);
}

console.log("all found results:", results);
let shortestResult = results.sort((a, b) => a.length - b.length)[0];
console.log("the shortest result is:", shortestResult);

Answer №3

After careful consideration, I ultimately chose this particular solution for its impressive effectiveness, straightforwardness, and optimized performance:

let seq = "us warship";
let source = "The traditional US adversary has also positioned a spy ship off the coast of Delaware and carried out flights near a US Navy warship, concerning American officials.";

let re = new RegExp(`\\b${seq.replace(/\s/g, "\\b.+?\\b")}\\b`, "gi");
let snippet = null;
let matches;
while (matches = re.exec(source)) {
  let match = matches[0];
  if (!snippet || match.length < snippet.length) {
    snippet = match;
  }
  re.lastIndex -= (match.length - 1);
}
console.log(snippet); // "US Navy warship"

Source:

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

Order JSON Array Using LoDash Library

Recently I encountered a JSON array with the following structure: var json = [ { key: 'firstName', value: 'Bill' }, { key: 'lastName', value: 'Mans' }, { key: 'phone', value: '123.456.7890&apo ...

Struggling to send the correct cookies to the API server using Next.js

I have set up an API express server on api.mydomain.com and a Next.js website on mydomain.com. My Next.js application uses getServerSideProps to request data from the API for displaying on the page. However, I am facing an issue where I can set cookies for ...

Next.js - Anticipated that the server HTML would include a corresponding <div> within <div> tag

For a live demonstration, please click here In my current project, I am experimenting with creating a simple layout that adjusts based on the user's screen size. Specifically, on mobile devices, only the latest posts should be displayed. On desktops, ...

I'm looking for an easy way to generate a special effect when my mouse interacts with a div using HTML, CSS, or JavaScript

I'm attempting to replicate this interesting effect where a div is surrounded by a container when the mouse hovers over it. It looks pretty cool, like in this image here: https://i.stack.imgur.com/p0epq.png Does anyone have any suggestions on how I ...

Tips on resolving the issue of an Axios post request not appearing in a get request in React

When using axios to make a post request in this code, a new username is posted, but there is an issue with retrieving the posted name from the API. How can I fix this problem to view my posted request? const App = () => { const [data, setData] = u ...

In React (Next.js), the act of replacing a file is performed instead of adding a file

I kindly request a review of my code prior to making any changes. const test = () => { const [files, setFiles] = useState ([]); //I believe I need to modify the following statement. const handleFile = (e) => { const newFiles = [] for (let i= ...

Utilize the parsing functionality in three.js to extract JSON geometry data

After exporting a model from Blender using the three.js exporter and successfully loading it with the JSONLoader, my next challenge is to store the JSON information in a variable and parse it to display the model without having to load an external file. T ...

Error message: Unable to access properties of undefined object (reading 'authorization')

This is a snippet of code that handles user authentication and authorization const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const userRepository = require("../repositories/userRepository"); const SALT ...

Efficiently transferring components of a JavaScript project between files

For the first time, I am creating an npm package using ES6 and Babel. However, I am facing difficulties in connecting everything together so that it can be imported correctly by the end user. The structure of my build (output) folder is identical to src: ...

Transferring information from parent page to child page using Angular version 8.2.4

As a newcomer to Angular, I am facing a challenge in sharing data between pages upon loading the main page. The structure involves using dynamic forms to generate dynamic pages within the main page. However, when trying to pass data from the main page to t ...

What sets returning a promise from async or a regular function apart?

I have been pondering whether the async keyword is redundant when simply returning a promise for some time now. Let's take a look at this example: async function thePromise() { const v = await Inner(); return v+1; } async function wrapper() ...

What is the best way to synchronize the state of a single React component across various pages?

I am currently working on a React Component that includes a toggle feature (on or off) with the state being managed by the component's own state (this.state). My dilemma is ensuring that this state remains when the user navigates from one page to ano ...

Eliminating duplicate loading of jQuery in Django SmartSelect

I'm facing an issue with Django's app, smart select, as it tries to load jQuery on its own. I've already loaded jQuery in the header and then loaded JQuery UI related stuff. However, smartselect also loads jQuery again in the body, causing p ...

The powerful combination of Ajax and Django creates a dynamic Like button

Encountering difficulties while trying to implement a basic like button feature. Despite following various tutorials, clicking on the Like button does not yield any action. See below: models.py class Comentario (models.Model): titulo = models.CharFie ...

Having issues with the latest version of Fabric JS code running properly

Hello, I stumbled upon this JS fiddle (http://jsfiddle.net/efmbrm4v/2/) and I really need something similar to function properly. The fiddle uses an older version of fabric js (1.4.0) and I'm having trouble getting it to work with the newer versions ( ...

What is the best way to put together the perfect attire for Threejs shaders?

I have been experimenting with using Three.js' built-in ShaderChunks for implementing lighting and fog effects, and I decided to start by mimicking a setup from one of the ShaderLib shaders. Initially, I utilized the following code snippet: customMat ...

Retrieve an array containing various values of a single element with the help of Protractor

Currently, I am in the process of testing an application that showcases graphs using rickshaw and d3. The tests are being run with protractor and jasmine. It's worth noting that this question is not specific to this particular scenario but rather more ...

Steps to selectively enable or disable checkboxes in a dynamic table depending on a dropdown selection

I'm currently facing an issue with a dynamically generated HTML table from a JSON file. Each row in the table consists of a dropdown list and a checkbox. I need the checkbox to be disabled when the default value is selected in the dropdown, and enable ...

Utilizing jQuery to dynamically convert a dropdown into a multiselect when triggered by the selection of another dropdown within a form containing cloned

After coming across discussions on using a multiselect based on another multiselect, cloning a form row, and dynamically updating select options, it seems there are no answers detailing how to combine all three concepts together. In my particular scenario ...

Utilizing jQuery ajax to dynamically update map markers on Google Maps at intervals

I am currently working on a project that involves updating a Google map with a marker at regular intervals. I have an Ajax request that retrieves a single latitude and longitude coordinate, but I'm struggling to display it on the map. One option coul ...