Regex search without truncating repetitions

I am trying to locate patterns in strings where a character is followed by another character, and then followed by the first character again.

For instance, in the string "abab" I am looking for "aba" and "bab".

/([a-z])[a-z]{1}\1/g

But when I run this code, it only returns the first result (I am working with JavaScript).

"abab".match(/([a-z])[a-z]{1}\1/g)
["aba"]

When I try with "ababcb", it gives two matches instead of three (I should get "aba", "bab", "bcb").

"ababcb".match(/([a-z])[a-z]{1}\1/g)
["aba", "bcb"]

I suspect the regex is repeating on the truncated string, finding the first match and then proceeding with the rest. How can I prevent this behavior and find all possible matches?

Answer №1

Using a Positive Lookahead allows you to capture the following patterns:

var re = /(?=(([a-z])[a-z]\2))./g, matches = [];
while (m = re.exec('abab')) {
   matches.push(m[1]);
}
console.log(matches) //=> [ 'aba', 'bab' ]

var re = /(?=(([a-z])[a-z]\2))./g, matches = [];
while (m = re.exec('ababcb')) {
  matches.push(m[1]);
}
console.log(matches) //=> [ 'aba', 'bab', 'bcb' ]

Answer №2

Here is a regex pattern using lookahead:

var re = /(\w)(?=(\w\1))/g;
var input="abab";
var matches = [];

while (match = re.exec(input)) {
   matches.push( match[1] + match[2] );
}

console.log(matches);
//=> ["aba", "bab"]

Another Example:

input="ababcb";
matches = [];    
while (match = re.exec(input)) {
    matches.push( match[1] + match[2] );
}

console.log(matches);
//=> ["aba", "bab", "bcb"]

Check out the 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

Modify the checkbox's initial value prior to submission

I'm having a small issue. I am generating a checkbox list where the checkboxes are checked if the JSON value inside them is true and unchecked if the JSON value is false. So, if the checkbox is checked, the corresponding line of HTML looks like this: ...

jQuery puzzle: a form within a form within a form

I am facing a bit of a dilemma with a partially working solution. The scenario is this - I am using a basic .load() function attached to a <select> element to fetch another form populated through PHP/MySQL. What I intend to achieve is for this newly ...

Next.js version 10.0.5 presents an issue with undefined environment variables

I recently started building a website using Next.js and encountered an issue while trying to integrate Google Tag Manager. Despite following the tutorial provided in the Next.js Github example, I found myself unable to access my environment variables. ...

What is the best way to manage a multi-select dropdown with checkboxes in Selenium Webdriver?

Below is a snapshot of the drop-down I am working with. In order to handle multiple selections, I currently have code that clicks on the arrow in the drop-down and then selects the corresponding checkbox. However, I would like a more efficient solution fo ...

Adjustable <a> component

There is this element: <a id="lnkViewEventDetails" class="psevdo calendar-event event" style="height: 126px;" href="/someurl/895?responseType=5" onclick="event.stopPropagation();"> I am trying to make it resizable using JQuery UI: $("#lnkViewEvent ...

What is the method to conceal an element after detecting and locating a specific class using jQuery?

Can someone please assist me today with the following task: Step 1: <div id="htmlData"> <div class="col-md-12"> <div class="pull-left"> <h3>Report: <strong>Travel </strong></h3> ...

Next.js app experiencing issues with Chakra UI not transitioning to dark mode

After attempting to incorporate Chakra UI into my Next.js application, I carefully followed every step outlined in their documentation: Despite setting the initialColorMode to "dark" for the ColorModeScript prop, it seems that the dark mode is not being a ...

In jqGrid's gridComplete event, we can use the getRowData method to retrieve the value of a

Seeking guidance on extracting variables from jqGrid getRowData method While iterating through rows, I simply want to retrieve the ID and Phrase column values into separate variables gridComplete: function () { var allRowsInGrid = $('#list'). ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

Incorporating jQuery ajax requests into divs seamlessly to avoid any page disruptions

When loading numerous ajax calls on a page, the timing of each call varies, resulting in some content loading before the user reaches the top of the page. This may cause the user to miss viewing certain data unless they scroll back up to the top. Below is ...

Combine the common id field from two distinct arrays in AngularJS

I have two distinct arrays of data objects, each containing multiple fields: https://i.stack.imgur.com/tMM4l.png https://i.stack.imgur.com/ScgPh.png Here is an example of the data object array with the inclusion of the eventId field. https://i.stack.imgur ...

When extracting a value from an HTML textarea that contains multiple lines of text inputted by the user, the JSON becomes invalid

Here is the JSON format I am working with: { questionID: int studentAnswer: "String" } The issue I am facing is that the studentAnswer field is currently only capable of holding input from a single line in an HTML textarea. If I input text that spa ...

The Fuel-ui module in Angular 2 fails to function properly when loaded from a different directory

We recently switched from ng-cli to Gulp for building our Angular2 project, and we are utilizing Fuel-ui. An unusual error has come up. We have incorporated Fuel-ui's alert component into one of our components. When referencing fuel-ui from node_mo ...

The apploading feature in my React Native is not functioning correctly, so I am unable to use it as intended

Every time I run my code, I encounter this error: error screenshot This is the code snippet I am using to import custom Google fonts: import React, { useState } from "react"; import Home from "./screens/home"; import { View } from &quo ...

I am puzzled by the fact that my data is showing as undefined even though I have logged it to the console in

I am currently working on an app using React for the frontend and Node.js for the backend, which connects to a cloud-based MongoDB instance. Although I can successfully retrieve data from the database and see it logged in the console, the returned result i ...

AngularJS array not refreshing following an AJAX request

Currently, I am still in the process of familiarizing myself with Angularjs and actively learning about its functionalities. One issue I have encountered is that when I define an array and loop through it using "ng-repeat," the items within ng-repeat fail ...

Subtract and include characters in a string

Can you help me swap out \n for a new line? Below is the content retrieved from the database: <!DOCTYPE html>\n<html>\n<body>\n<div>\n<label class=\"s20 c03\">Label</label>\n< ...

Having trouble with accessing properties like `d3.svg()`, `d3.scale()` and other features of d3js within an Angular 2 environment

Struggling to incorporate d3.js into angular2. Below is the command I used to install d3 in Angular2: npm install --save d3 install --save-dev @types/d3 This is how my package.json appears: { "name": "my-app", "version": "0.0.0", "license": "M ...

Issue with splitting an array and eliminating commas - angular/ReactJS

Console Error: Unhandled error during execution of mounted hook Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'split') It seems to work up until it comes across a group that has no data for continent. This looks ...

Exploring a different approach to utilizing Ant Design Table Columns and ColumnGroups

As per the demo on how Ant Design groups columns, tables from Ant Design are typically set up using the following structure, assuming that you have correctly predefined your columns and data: <Table columns={columns} dataSource={data} // .. ...