How can I create a regex pattern that will exclude characters within parentheses?

While working on some regex, I encountered a bug:

The scenario is as follows: I have this string - for example

"+1/(1/10)+(1/30)+1/50"
and I applied the regex /\+.[^\+]*/g to it,
which worked perfectly giving me
['+1/(1/10)', '+(1/30)', '+1/50']

However, the real issue arises when the + is within the parentheses ()

For example:

"+1/(1+10)+(1/30)+1/50"

This results in

['+1/(1', '+10)', '+(1/30)', '+1/50']
, which is not the desired output... What I want is
['+1/(1+10)', '+(1/30)', '+1/50']

So, the question is how can I ignore the parentheses in regex?

Any suggestions on how to accomplish this in regex?


Here is my Javascript code:

const tests = {
      correct: "1/(1/10)+(1/30)+1/50",
      wrong  : "1/(1+10)+(1/30)+1/50"
}

function getAdditionArray(string) {
      const REGEX = /\+.[^\+]*/g; // need to modify this regex to ignore the () even if they contain the + sign
      const firstChar = string[0];

      if (firstChar !== "-") string = "+" + string;

      return string.match(REGEX);
}

console.log(
    getAdditionArray(test.correct),
    getAdditionArray(test.wrong),
)

Answer №1

To find a specific pattern, you can exclude matching parenthesis first and then optionally match anything inside parentheses.

\+[^+()]*(?:\([^()]*\))?

This pattern will:

  • \+ Match a plus sign
  • [^+()]* Match any characters except for plus signs or parentheses
  • (?: Non-capturing group to match everything within parentheses
    • \([^()]*\) Match whatever is between parentheses
  • )? Close the non-capturing group and make it optional

For more specific matches on digits, plus signs, and slashes, consider using a character class in your regex pattern.

\+(?:\d+[+/])?(?:\(\d+[/+]\d+\)|\d+)

Check out another demo of this pattern on Regex101.

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 Javascript code I wrote is unable to detect the array element that was initially defined in Python

Trying to launch a new browser window through Selenium using driver.execute_script("window.open('');") However, the goal is to open a specific link provided by the user. For this purpose, extracted the link input from an array and inc ...

Node.js and Express: Delivering Seamless Video Streaming via HTTP 206 Partial Content

Having a binary file like an mp4 video in a MarkLogic database, I am utilizing the Node.js API of the database to stream this document in segments. The structure is as follows: html document <video controls="controls" width="600"> <source src= ...

Tips for utilizing 'toHaveClass' to find a partial match in Jest?

When I assign the class success to an element, React-Mui appends additional text to it in the DOM, such as mui-AbcXYZ-success. This causes my test using the code snippet below to fail: expect( getByTestId('thirdCheck')).toHaveClass("success ...

Several middlewares using router.params()

Is it possible to include multiple middlewares as parameters in the function router.params() in Node-Express? I currently have the following setup: const checkAuth = (req, res, next) => {console.log("checking auth"); next()} const checkAuth = ...

Error encountered when executing the npm run dev script

Attempting to follow a tutorial, I keep encountering an error related to the script. I've tried restarting the tutorial to ensure I didn't overlook anything, but the same issue persists. Working on a Mac using pycharm. In the tutorial (from Ude ...

Warning: npm is resolving peer dependency conflicts during the installation process

Upon running npm install for my React application, I encountered the following warnings in the logs. Despite that, the npm installation completed successfully and the dependencies were added under node_modules. My app even starts up without any issues. I ...

The Resharper guideline "Function Parameter" doesn't allow the usage of AngularJS service names

I have a question regarding naming conventions in my AngularJS app. Currently, all my service names start with an uppercase character. However, I am facing an issue where service parameters must match the service name, but Resharper's JavaScript "Func ...

Linking promises together ensures that they always resolve with a result

My understanding of how to chain promises is still not completely solid. What I am trying to achieve is as follows: I have a promise that can either resolve or reject. The following code checks for this and continues if the promise resolves, or stops if i ...

Changing the ng-src attribute with a custom service in an AngularJS application

Check out this Pluker I created for making image swapping easier. Currently, the images swap normally when coded in the controller. However, I am interested in utilizing custom services or factories to achieve the same functionality. Below is the code snip ...

Bidirectional binding with complex objects

In my Angular2 app, I have a class called MyClass with the following structure: export class MyClass { name: Object; } The name object is used to load the current language dynamically. Currently, for two-way binding, I am initializing it like this: it ...

Error: Vuex commit fails due to JSON circular structure issue

Using Vue.js along with the vuex store, I make an API call to validate an item, which returns arrays of errors and warnings. Below is my vuex action : export function validateitemReview ({ commit, dispatch, state }, { reviewId, type, itemreviewData }) { ...

What is the best approach for making a drawer resizable?

I am interested in making the material ui drawer resizable width using a draggable handle. Currently, I have implemented a solution that involves adding a mouse event listener to the entire application and updating the width based on the position of the ...

Creating dynamic web pages with jQuery is a simple and effective

I am currently using jQuery to create HTML elements with specific classes and then append them together. However, the code I have written is not adding the generated HTML to the container as expected. There are no errors being produced but the HTML is not ...

Guide on invoking a node.js function from an express-rendered ejs page

My express server currently has a button that triggers a POST request to activate a function in my node.js server. Instead of using a traditional POST request, I am interested in implementing something like AJAX so that the page doesn't reload. Is th ...

Using the MoveToElement and click functions in Protractor with Node.js for automated browser

Trying to click on a checkbox in our application. I have successfully implemented it in Selenium Java using the code below, but struggling to do the same in Protractor Node.js. Any assistance would be appreciated. Selenium- Java : Actions actions ...

What steps do I need to take to develop a CLI application similar to ng, that can be installed globally on the system

Upon installing npm i ng -g How does the system determine the installation path? I am interested in creating an application that can be installed and executed similarly. ...

What is the correct way to establish a Cookie (header) using XMLHttpRequest in JavaScript?

I am attempting to set a cookie in an XSS request using XMLHttpRequest. After reviewing the XMLHttpRequest Specification, I discovered that section 4.6.2-5 indicates that setting certain headers like Cookie and Cookie2 may not be allowed. However, I am lo ...

Styling Javascript Objects

[ [ {"path":"path2","value":"kkk"}, {"path":"path0","value":"uuu"}, {"path":"path1","value":"ppp"} ] ] The result obtained from my manipulation is shown above. However, I require the format to be as depicted below: ["path":"pat ...

Maximum Age Setting for Iron Session Cookie

Currently, I am attempting to configure a Next JS application with iron-session and a 'remember me' feature. The objective is for the maxAge of the iron-session cookie to be extended to a week if the user selects the remember me option on the log ...

Sorting files in jquery file upload

Has anyone had experience using the jQuery-File-Upload library from https://github.com/blueimp/jQuery-File-Upload? I'm currently facing an issue and wondering if anyone could assist me in sorting the files in a different manner. By default, this scrip ...