Pattern matching in JavaScript using regular expressions is used to identify and extract repeating patterns,

There is a specific string that contains structured data and multiple instances of @doc { within it. I need to extract these occurrences, making sure the result includes two unique matches.

To achieve this, regular expressions come in handy:

var matches = str.match(/\@doc \{[^\}]+\}/gm);

However, the challenge arises when the string also contains JSON objects as values, altering the structure:

In such cases, an attempt was made to modify the regex pattern by excluding instances of @doc from the matches:

str.match(/\@doc \{(?!@doc)+}/gm)
str.match(/\@doc \{(?!@doc)*}/gm)
str.match(/\@doc \{[\s\S]+(?!\@doc)\}/gm)
str.match(/\@doc \{(?!@doc)[\s\S]+}/gm)
str.match(/\@doc \{(?!\@doc)+\}/gm)

It seems like my approach towards excluding the word @doc using these regex patterns might be incorrect. What would be the most effective regex solution for this scenario?

Answer №1

You're so close! All you need to do is place the negated character class inside a capturing group and then store the contents of the first capturing group into an array.

/\@doc \{([^\}]+)\}/g

Here's an example:

> var str = '"/**' +
... '\n* @doc {' +
... '\n*   description: "Invalid login without user", ' +
... '\n*   request: "/v2/login", ' +
... '\n*   response: "login-invalid-user.json"' +
... '\n* }' +
... '\n*/' +
... '\n some code goes here' +
... '\n some code goes here' +
... '\n some code goes here' +
... '\n/**' +
... '\n* @doc {' +
... '\n*   description: "Invalid login without user", ' +
... '\n*   request: "/v2/login", ' +
... '\n*   response: "login-invalid-user.json"' +
... '\n* }' +
... '\n*/"';
undefined
> var re = /\@doc \{([^\}]+)\}/g;
undefined
> var m;
undefined
> while ((m = re.exec(str)) != null) {
... console.log(m[1]);
... }

*   description: "Invalid login without user", 
*   request: "/v2/login", 
*   response: "login-invalid-user.json"
* 

*   description: "Invalid login without user", 
*   request: "/v2/login", 
*   response: "login-invalid-user.json"

The blank line between the two examples occurs because the regex also captures the newline character immediately following the { bracket.

Update:

> var str = '"/**' +
... '\n* @doc {' +
... '\n*   description: "Invalid login without user", ' +
... '\n*   request: {url: "/v2/login1"}, ' + // <--- THIS HAS BEEN CHANGED
... '\n*   response: "login-invalid-user.json"' +
... '\n* }' +
... '\n*/' +
... '\n some code goes here' +
... '\n some code goes here' +
... '\n some code goes here' +
... '/**' +
... '\n* @doc {' +
... '\n*   description: "Invalid login without user", ' +
... '\n*   request:  {url: "/v2/login2"}, ' + // <--- THIS HAS BEEN CHANGED
... '\n*   response: "login-invalid-user.json"' +
... '\n* }' +
... '\n*/"';
undefined
> var m;
undefined
> var re = /\@doc \{([\S\s]*?)\}(?=\n)/g;
undefined
> var m;
undefined
> while ((m = re.exec(str)) != null) {
... console.log(m[1]);
... }

*   description: "Invalid login without user", 
*   request: {url: "/v2/login1"}, 
*   response: "login-invalid-user.json"
* 

*   description: "Invalid login without user", 
*   request:  {url: "/v2/login2"}, 
*   response: "login-invalid-user.json"
* 
undefined

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

Content Security Policy directive violation: Chrome extension policy error occured due to refusal to execute inline event handler

I've been working on a chrome extension to perform a simple task, but I've hit a roadblock with one line of HTML code that's causing issues with setting the correct permissions. Despite my efforts, I'm stuck on what exactly needs to be ...

What is the best way to set a newly selected HTML option as the first choice?

I'm facing a simple problem in JavaScript that I can't seem to crack. Admittedly, I am new to working with JavaScript. My issue lies with sorting a dropdown list in alphabetical order while also keeping the selected value at the top. Whenever a ...

Steps to alter the color of a JSONLoader-generated object with a simple click

Recently, I've been delving into Three.js and managed to create an object using the JSONLoader. The material of the object is currently grey in color. My goal now is to allow users to change the color of the object by clicking on a button that I have ...

Enable swipe functionality for mobile users

Looking to make the code below swipable on mobile devices. Any suggestions or resources to achieve this would be greatly appreciated! <script> var links = document.querySelectorAll(".heart"); var wrapper = document.querySelector("# ...

The quantity of elements stays constant even after adding to them using Javascript

I have implemented a notes list feature that allows users to add notes using an input field. Beneath the notes list ul, there is a message showing the total number of notes: $('li').length. However, I encountered an issue where the count of not ...

Navigating with React Router using URL parameters

After implementing react router with a route path taskSupport/:advertiserId that includes parameters, I encountered an issue when trying to access the link http://localhost:8080/taskSupport/advertiserId. My browser kept returning 404 (Not found) errors for ...

JavaScript error: You are trying to use Array.find() in Redux, but it

I am currently developing a react native application and I am using basic redux for managing the state, although I am a complete beginner to this. In a specific issue, I am facing an issue while fetching data from my redux store in the edit screen where th ...

Using Npm to install a module results in an abundance of files being provided

Back when I used npm install 6 months ago to install a module, it would create a new folder under node_modules containing all the files for that module. However, now when I use it, it creates multiple files for one module. How can I install a module to a ...

Using a render target causes certain elements of my visual graphics to become hidden

Hey there, I've been experimenting with render targets lately and encountered some issues. I've put together a simplified example below: init = function() { // RENDERER canvas = document.getElementById("mycanvas"); renderer = new THREE ...

What could be causing the data in getServerSideProps to be altered?

After fetching data from an API and passing it to index.js using getServerSideProps, I noticed that the prop array is initially in order by rank [1, 2, 3, etc]. Here's an example of the data: [ {rank: 1, price: 123}, {rank: 2, price: 1958}, {rank: ...

The Socket IO Client is receiving a different object than the one that was sent by the Server

My server side code is sending an object to the client side, but the object received by the client is completely different from what was sent. Let me elaborate: Code Server side code: //Setting up the example var response={}; response.models=[]; respo ...

I am unable to retrieve images using the querySelector method

Trying to target all images using JavaScript, here is the code: HTML : <div class="container"> <img src="Coca.jpg" class="imgg"> <img src="Water.jpg" class="imgg"> <img src="Tree.jpg" class="imgg"> <img src="Alien.jpg" class=" ...

Can you demonstrate how to convert a string date array into a JavaScript array?

I am facing a challenge where I need to convert a string representation of an array into a JavaScript array for the purpose of looping. The string in question is enclosed within single quotes. Inside my JavaScript code, I have the following: var length1 ...

Tips for creating JavaScript validation for the Amount input field (in the format 22.00) in an ASP.NET application

In this aspx page using ASP.NET 4.0, there is a text box where users can enter a rate. The requirement is that only numbers are allowed to be entered. For example, if the user enters 22, it should display as 22.00. If the user enters 22.5, it should displa ...

We regret to inform you that the request cannot be processed by our Express

Currently, I am in the process of learning nodejs and expressjs and attempting to integrate it into the Spring MVC pattern. My intention behind this is to maintain cohesion within my files. However, the results are not quite aligning with my expectations.. ...

Interactive table on click

Seeking assistance with an issue involving a combobox (select) and a dynamic table generated from PHP. The table displays names along with their Firstname, Lastname, and ID (hidden). Upon clicking on a row in the table, I should retrieve the ID of that spe ...

Switch up the Yii ListBox default onChange event to utilize AJAX with onClick instead

Below is the code I have for a <select> element: $htmlOptions = array( 'size' => '20', 'ajax' => array( 'type' => 'POST', 'url' => Y ...

Endless asynchronous loops with setInterval()

My nodejs application requires multiple infinite loops that call asynchronous functions. I was contemplating the following approach: async function process1() { ...perform some asynchronous tasks... } async function process2() { ...perform some as ...

What impact does adding 'ng' in unit tests have on how promises are handled?

Here is an example of a service that utilizes $q.when to wrap a promise from a third-party library: // myService.js angular.module('myApp', []) .service('myService', function($q, $window) { var api = new $window.MyAPI(); this ...

Combine the serialized form data along with an array and post them together

I am encountering difficulties with sending the form through ajax. Along with the information input by the user, I also need to include an array of objects in the data being sent. AJAX POST: submitHandler: function (form) { $.ajax({ ...