JavaScript, Regular Expressions for splitting a string into a multidimensional array based on parentheses

I am facing difficulty in splitting the input string into an array:

'((Application = smtp AND "Server Port" != 25) AND (Application = smtp AND "Server Port" != 25)) OR (Application = pop3 AND "Server Port" != 110) OR (Application = imap AND "Server Port" != 143) AND (Application = imap OR "Server Port" != 143)'.split(/\(([^)]+)\)/g)

Result obtained:

["", "(Application = smtp AND "Server Port" != 25", " AND ", "Application = smtp AND "Server Port" != 25", ") OR ", "Application = pop3 AND "Server Port" != 110", " OR ", "Application = imap AND "Server Port" != 143", " AND ", "Application = imap OR "Server Port" != 143", ""]

Desired result:

["", "(Application = smtp AND "Server Port" != 25) AND (Application = smtp AND "Server Port" != 25")", OR ", "Application = pop3 AND "Server Port" != 110", " OR ", "Application = imap AND "Server Port" != 143", " AND ", "Application = imap OR "Server Port" != 143", ""]

Note the content of the 1st index

"(Application = smtp AND "Server Port" != 25) AND (Application = smtp AND "Server Port" != 25")"

Any suggestions for achieving this using RegEx?

EDIT Formatted version:

The input string I have is as follows:

(
   (
     (App = smtp AND "Server Port" != 25) 
     OR 
     (App = pop3 AND "Server Port" == 20)
   ) 
   AND 
     (App = smtp AND "Server Port" != 35)
 ) 
OR 
(App = pop3 AND "Server Port" != 110) 
AND 
(
   (App = imap AND "Server Port" != 143) 
   OR 
   (App = pop3 AND "Server Port" == 20)
) 
AND (App = imap OR "Server Port" != 143)

Transformation needed:

[
    [
         [
           'App = smtp AND "Server Port" != 25', 
           'OR', 
           'App = pop3 AND "Server Port" == 20'
         ], 
      'AND', 
      'App = smtp AND "Server Port" != 35'
    ], 
   'OR', 
   'App = pop3 AND "Server Port" != 110', 
   'AND', 
   [      
     [
       'App = imap AND "Server Port" != 143', 
       'OR',
       'App = pop3 AND "Server Port" == 20'
     ]
   ], 
   'AND', 
   'App = imap OR "Server Port" != 143'
]

Answer №1

There have been suggestions to create a flattened array and then handle each inner array with the split method, which is considered a better approach. However, for the sake of argument, if you insist on using regex, here is an unconventional solution:

    var str = '((Application = smtp AND "Server Port" != 25) AND (Application = smtp AND "Server Port" != 25)) OR (Application = pop3 AND "Server Port" != 110) OR (Application = imap AND "Server Port" != 143) AND (Application = imap OR "Server Port" != 143)';

    var final = str.replace(/\((?!\()/g,"['")        //replace ( with [' if it's not preceded with (
               .replace/\(/g,"[")                //replace ( with [
               .replace/\)/g,"']")              //replace ) with '] 
               .replace/\sAND\s/g,"','AND','")   //replace AND with ','AND','
               .replace/\sOR\s/g,"','OR','")     //replace OR with ','OR','
               .replace/'\[/g,"[")               //replace '[ with [
               .replace/\]'/g,"]")               //replace ]' with ]
               .replace/"/g,"\\\"")              //escape double quotes
               .replace/'/g,"\"");             //replace ' with "
    console.log(JSON.parse("["+final+"]"))

Answer №2

Give this a try and see if it works:

\(([^O]+|[^(]+)\)

This is how the full code would look like:

console.log('((Application = smtp AND "Server Port" != 25) AND (Application = smtp AND "Server Port" != 25)) OR (Application = pop3 AND "Server Port" != 110) OR (Application = imap AND "Server Port" != 143) AND (Application = imap OR "Server Port" != 143)'.split(/\(([^O]+|[^(]+)\)/g))

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

Troubleshooting Vue.js 2 Routing Issues: Difficulty Accessing Posts Variable

My first venture into Vue.js involves working with WP REST API. Initially, all my posts are displayed perfectly. However, when I attempt to integrate Vue-router, the component responsible for showcasing all the posts, 'home-post-list', breaks do ...

What is the method for deactivating body parser json and urlencoded specifically on certain website links?

let shouldParseRequest = function (req) { let url = req.originalUrl; return (url.startsWith('/api/payments/stripe-webhook') || url.startsWith('/uploadimg')); } let parseJSON = bodyParser.json({ limit: '900kb' }); let u ...

Accessing only the visible elements using vanilla JavaScript

Here are some elements I have: <div class="one">send Message</div> <div class="one">send Message</div> <div class="one">send Message</div> In a web page, there are send buttons like the ones above. Only one button is ...

Can we load the form using an ajax request and then submit the form using ajax as

So I have a situation where I am loading a form into a page using an ajax call as shown below: $('.ajax_click').on('click', function(event) { event.preventDefault(); /* Act on the event */ var getmsgtoload = $(this).find(&ap ...

JavaScript function is not callable

Currently facing a strange issue or maybe it's just me missing something obvious. I've searched for the error but couldn't find the right solution. I am attempting to execute some Javascript code when the key "/" is pressed in a text box. ...

What is the best method to save changes made in a webdatagrid to a session?

My goal is to set the datasource of a grid to a session variable, bind it, and then add a row or rows to the dataset and save the changes back to the session. However, I am encountering an issue after trying to commit the changes, resulting in an AJAX sync ...

Tips for zooming to the middle of a div element

I'm trying to figure out how to create a zoom in effect on my large div, but I haven't been successful despite searching through many resources. My goal is to zoom into the center of the user's screen rather than just at a set position. ht ...

Is safeguarding JSON data in Javascript important?

After employing jQuery Ajax to communicate with a php script, it retrieves JSON data. This JSON Array Object is then stored in a JavaScript Variable called var myJSON = ajaxReturn; Typically, the JSON values returned are not visible in the Page Source or ...

Include a new button in the react material-table toolbar

I am looking to enhance the material-table toolbar by adding a new button. This button will not be directly related to the table, but instead, it will open a modal window with additional information. The button I want to add is called "quotations" and I w ...

Creating a Node server exclusively for handling POST requests is a straightforward process

I'm looking to set up a Node server that specifically handles POST requests. The goal is to take the data from the request body and use it to make a system call. However, my current setup only includes: var express = require('express'); var ...

A step-by-step guide on arranging the index of items in an array based on the values within each object in

I have a collection of objects, each representing a color along with a corresponding "weight" value. The weight values are dynamic and vary based on the analyzed image. I need to organize this array in such a way that the objects with the highest weight ...

Tips for extracting <span> element values from an array and saving them in a new array using Javascript

I have a list of countries with unique identifiers attached to them using a <span> element. Here is an example: var countryList = [ 'Asia <span class="hide">1234</span>', 'Ireland <span class="hide">65d ...

Is it just me, or does Array.prototype.sort() only function properly in Firefox and not

I am currently working on a Next.JS Webapp and I have encountered an issue. Prior to saving my data to a useState object for use in the webapp, I implement this code snippet to arrange an array of objects by a specific date field. person_json[0].events.sor ...

Encountering an issue: ReferenceError: regeneratorRuntime is not defined when implementing react-speech-recognition in nextjs13

Encountering the errorReferenceError: regeneratorRuntime is not defined in my NextJS project I'm currently using Redux toolkit. Link to my project. Please note that the code triggering the error can be found under the nextjsfrontend branch. I' ...

Display properties of a JSON object using VUEJS

How can I efficiently read JSON data in my VueJS code? Here is the code snippet: <template> {{data}} </template> <script> import axios from 'axios'; export default { data() { return { data: null }; }, mou ...

Automate Cart Updates with Increment and Decrement Buttons on the Cart Page of Magento 2 Store

On the cart page, I've added buttons to increase (+) and decrease (-) the quantity of a product. How can I make it so that the quantity updates automatically without needing to click on the update shopping cart button? Any suggestions on how to solve ...

Dynamic Weight feature in Prestashop allows for automatically adjusting shipping costs

I'm curious about displaying the dynamic weight of each product combination on my product page. Currently, I have something like this: {l s='Weight: ' js=1}{sprintf("%1\$u",$product->weight)}&nbsp{Configuration::get('PS_WEI ...

Converting Dates with Ractive.js

Is there a way to transform the Epoch time value retrieved from a JSON endpoint into a readable time string format such as "Tue 19 Jan 11:14:07 SGT 2038" without relying on external libraries like moment.js? var ractive = new Ractive({ el: '#cont ...

unable to simultaneously scroll two elements

Within the realm of reactjs, I've crafted a function that smoothly scrolls elements by utilizing a useRef: ref.current?.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center", }); ...

Is there a way for me to verify that the input value matches an email format?

Here is an example that I'm struggling with: link This is the HTML code: <input type="text" name="email" class="email" placeholder="Your email address"> This is the JavaScript code: $(document).ready(function ($) { function validateEm ...