Reverse capture group combined with forward capture group

Does the title not just sum it up? I'm attempting to gather groups and merge them together.

Here's the text in question:

GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48

And this is what I desire as output:

IDENTIFIER 10.802.123/3843-48

So, just to be clear, I aim to capture a group before and after a specific word, then concatenate the two using only regex. Feasible?

I've managed to extract 48 in the following manner:

var text = GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48
var reg = new RegExp('IDENTIFIER' + '.*?(\\d\\S*)', 'i');
var match = reg.exec(text);

Output:

48

Can it really be done?

My offer stands at 200 points.

Answer №1

Prior to extracting the desired groups, it is crucial to clearly define them. For instance, if you specify the group before the target word as consisting of four or more non-whitespace characters, and the group after the word as comprising one or more non-whitespace characters, you can utilize the subsequent regular expression.

var re = new RegExp('(\\S{4,})\\s+(?:\\S{1,3}\\s+)*?' + word + '.*?(\\S+)', 'i');
var groups = re.exec(text);
if (groups !== null) {
   var result = groups[1] + groups[2];
}

Lets delve into the inner workings of the regular expression. Take note that we need to escape the backslashes since we are crafting a regular expression within a string.

  • (\\S{4,}) captures a segment comprised of four or more non-whitespace characters
  • \\s+ matches one or more whitespace characters
  • (?: signifies the commencement of a non-capturing group
  • \\S{1,3} matches one to three non-whitespace characters
  • \\s+ matches one or more whitespace characters
  • )*? makes the non-capturing group match zero or more times, with minimal occurrences
  • word corresponds to the content stored in the variable word during compilation of the regular expression
  • .*? matches any character zero or more times, with minimal occurrences
  • (\\S+) captures one or more non-whitespace characters
  • the 'i' flag renders this a case-insensitive regular expression

Note how our utilization of the ? modifier enables us to capture the nearest groups preceding and succeeding the word.

To globally match the regular expression in the text, append the g flag. The following snippet illustrates how to extract all occurrences.

function forward_and_backward(word, text) {
  var re = new RegExp('(\\S{4,})\\s+(?:\\S{1,3}\\s+)*?' + word + '.*?(\\S+)', 'ig');
  // Find all matches and construct an array of results.
  var results = [];
  while (true) {
    var groups = re.exec(text);
    if (groups === null) {
      return results;
    }
    var result = groups[1] + groups[2];
    results.push(result);
  }
}

var sampleText = "  GPX 10.802.123/3843- 1 -- IDENTIFIER 48   A BC 444.2345.1.1/99x 28 - - Identifier 580 X Y Z 9.22.16.1043/73+ 0  ***  identifier 6800";

results = forward_and_backward('IDENTIFIER', sampleText);
for (var i = 0; i < results.length; ++i) { 
  document.write('result ' + i + ': "' + results[i] + '"<br><br>');
}
body {
  font-family: monospace;
}

Answer №2

Here is a code snippet for extracting specific information from text:

let inputText = 'GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48';
let regexPattern = /GPX\s+(.+?) \d .*?(IDENTIFIER).*?(\d\S*)/i;
let resultArray = regexPattern.exec(inputText);

let finalOutput = resultArray[2] + ' ' + resultArray[1] + '-' + resultArray[3];
//=> "IDENTIFIER 10.802.123/3843­-48"

Answer №3

The replace function can be used to achieve this task.

var string = 'GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48';
string.replace(/.*?(\S+)\s+\d+\s*-\s*(IDENTIFIER)\s*(\d+).*/, "$2 $1-$3");

Answer №4

^\s*\S+\s*\b(\d+(?:[./]\d+)+)\b.*?-.*?\b(\S+)\b\s*(\d+)\s*$

This regex pattern can be used to match specific text patterns in a string. When replaced with $2 $1-$3, it captures and rearranges the matched groups accordingly. You can test this regex pattern using the demo provided here.

var re = /^\s*\S+\s*\b(\d+(?:[.\/]\d+)+)\b.*?-.*?\b(\S+)\b\s*(\d+)\s*$/gm; 
var str = 'GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48';
var subst = '$2 $1-$3'; 

var result = str.replace(re, subst);

Answer №5

Utilizing the 'split' method is another approach:

let textPhrase = 'GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48';

let sections = textPhrase.split(/\s+/);

if (sections[4] == 'IDENTIFIER') {
    let finalResult = sections[4] + ' ' + sections[1] + '-' + sections[5];
    console.log(finalResult);
} 

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

The React-native application initialized using npx create-react-app encountered an error and could not launch

Hello there, A couple of months back, I developed an app using create-react-app. However, when I tried to run it with npm start, I encountered the following error message: react-scripts start It seems like there's an issue with the project depende ...

I am seeking assistance in transmitting data to my server utilizing Ajax, PHP, and mySQL without relying on a form

I have been researching tutorials on how to work with JavaScript without using forms. Currently, I have the JavaScript code that maps my answers based on clicks and generates an array shown in an alert. However, I am unsure if the Ajax request is sending i ...

Discover the magic of TransformToggle and slideToggle in Javascript, HTML, and CSS

Working on a website coding project and ran into an issue. Trying to utilize an img as a link to slideToggle content. It's working, but I'd like the img to rotate 90deg on the first click and -90deg on the second one. Any solutions are greatly ap ...

There was an issue with rendering: "TypeError: Unable to access the 'name' property of an undefined object" [Vue alert]

I encountered the following error message: TypeError: Cannot read property 'name' of undefined Here's the snippet from the Vue file where the error occurred: <tr v-for="user in fields.data" :key="user.id"> <td>{{ user.id ...

Can jQuery effortlessly glide downward, come to a stop, continue downward, and then move upwards?

My webpage features a large table created and populated automatically every minute using ajax. The code structure is as follows: $(document).ready(function(){ setInterval(function(){ $.ajax({ //code to call backend, get the data, ...

Secured interactions following authentication using React Query and NextAuth

After successfully signing in to my Nextjs app using NextAuth, I encountered an issue with sending authenticated requests to my API. The data returned after signing in appears to be for an unauthenticated user. I suspect that the problem lies in React Que ...

Encountering a TypeError with DataTables and Tabledit

I've been attempting to integrate DataTables with Tabledit, but I keep encountering the error message "TypeError: Cannot set properties of undefined (setting 'nTf')". The number of tags also matches up. Interestingly, if I comment out the " ...

Creating a bar chart by using d3.layout.stack() and parsing data from a CSV file

Mike Bostock's Stacked-to-Grouped example showcases a data generation method that I find intriguing. However, since I have my own data stored in a CSV file, my main focus is on deciphering his approach and adapting it to work with my data instead. // ...

Is it true that Safari restricts AJAX Requests following a form submission?

I've developed a JavaScript-based upload progress meter that utilizes the standard multipart submit method instead of submitting files in an iframe. The process involves sending AJAX requests during submission to retrieve the percentage complete of th ...

Implement strict mode with npm

Are there any potential downsides to not using 'use strict' in a node module published through npm? Is it advisable to omit it if I want the module to be easily usable by others? EDIT: I am specifically asking this question to understand if excl ...

Enhancing Slider Appearance in Material-UI (React)

I am currently working on a project that involves creating a slider with specific values using Material UI and React. I followed the basic implementation from the documentation, which seems to work without needing any additional CSS. However, when I integr ...

Is there a way to script the action of unchecking checkbox 1 when checkbox 2 is checked, and unchecking checkbox 2 when checkbox 1 is checked?

Is it possible to create a custom radio button behavior with two checkboxes? For example, if checkbox 1 is checked, can we automatically uncheck checkbox 2 and vice versa? ( Transforming checkboxes into radio buttons. ) <input type="checkbox" id="chec ...

Is it possible to dynamically toggle the availability of a form text input based on the selected value in a form

I need help with a form on my website. The form has an option to add custom text to clothing you purchase. You can choose yes or no using a selection statement, and there is also an input text field where you can enter the text. I want to make it so that w ...

What are the methods to validate various file formats in multer s3?

My objective is to effectively handle and validate video and image files using the multer middleware. The challenge lies in ensuring that there is only 1 video file and a maximum of 10 images. Additionally, I need to implement size validation for these fil ...

Adjusting iframe height based on its source URL using JQuery

Currently, I have implemented a script to adjust the height of YouTube iframes in order to maintain a 16:9 aspect ratio while keeping the width at 100% of the container. The challenge I am facing is ensuring that the script only affects YouTube videos and ...

JavaScript's connection to the CSS property visibility seems to be causing some issues

The Javascript code seems to be ignoring the CSS display property, even though it's set in the style sheet. I added a debugger statement and noticed that the display value was empty. I've been staring at this for some time now, so I must be overl ...

When transmitting data from the parent component to the child component, the data successfully passes through, yet the view fails to reflect the

I'm facing an issue with passing data from a parent component to a child component using props. Here is the code snippet I'm working with: <div id="root"> <my-component v-bind:account-types='accountTypes'> </my-c ...

Scope of an array being passed

I have a challenge of passing an array from one external .js file to another. The individual files are functional on their own, however, the issue arises when trying to pass the array from pickClass.js to displayStudent.js and displaying the names along wi ...

Identifying changes in value in any scenario, jQuery

When I click on a button and change the input value, I want an alert to display 'Ok Done', but it's not working as expected. The input value may contain both numbers and letters. $("#myTextBox").bind("change paste keyup", function() { ...

Changing the value in sessionStorage does not trigger the onChange event (Next.js)

When I use a custom hook to load data from session storage into an input field, I noticed that the onChange() function doesn't trigger if I delete the entire content of the input. However, it works fine if I add or delete just one character. This issu ...