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']

https://i.sstatic.net/tggcj.png

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

For example:

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

https://i.sstatic.net/1BRkS.png

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

Restricting the Vue for-loop results to display only the current item in use

Currently, I am utilizing a for-loop to retrieve all of my posts, followed by employing a partial to obtain a list of all the usersThatUpvoted on that post. <div v-for="p in posts" style="padding: 16px"> <div> &l ...

Having issue with jQuery popup not functioning correctly on the right side with the contact form. Is there anyone who knows how

Looking for a side slide popup that only accepts paragraph content? Want to add a contact form to it? Check out this fiddle - link here For a working example, visit - $(function() { // Slide from right to left $('#test2').PopupLayer({ ...

How can I convert the JSON array response from the API, which is of type string, back into an array?

Is there a way to change a string type array back into an array? var arr = '[ "abc", "def"]'; console.log(typeof arr) ==> String How can I convert it back into an array format? I'm receiving this string-formatted array from an API r ...

Only one instance of the Next.js inline script is loaded

Incorporating Tiny Slider into my Next.js application has been a success, but I am facing an issue with the inline script that controls the slider's behavior. The script loads correctly when I first launch index.js. However, if I navigate to another p ...

What is the best way to explore JavaScript text using Firebug?

The search function (magnifying glass) located at the top-right hand corner of Firebug does not have the capability to search within JavaScript blocks. For instance, if I have the following code snippet: <script type="text/javascript"> var fooBa ...

Remove a letter or letters from every row

Seeking assistance to resolve a problem with the '>' symbol. When emails are forwarded, some email clients automatically insert ">" symbols before each line of text. This can cause the email content to become difficult to read, as shown in ...

Retrieving data from a directive in an HTML table

Utilizing AngularJS, I am seeking a method to retrieve the value from an input located within a specific row in a table. Presented below is an input element. Upon clicking the "add" button, my objective is to extract the value corresponding to that partic ...

Transfer an object to $state.go

I'm having trouble solving this issue. Here's the state I am working with: var myState:ng.ui.IState = <ng.ui.IState> { url: '/new/{order.orderNumber}', controller: 'OrderController', controll ...

Is there a way for me to automatically update the contents of div x using Ajax whenever the contents of div y are changed with another Ajax call?

I've been struggling with this issue for quite some time now and haven't been able to find a solution. The situation is as follows: I have two divs, where div3 needs to update its content whenever div2 changes. Div2 is updated using ajax, so whe ...

Displaying HTML with AngularJS dynamic data-binding

Here is a sample view: <div ng-show=""> <div style='background-color: #13a4d6; border-color: #0F82A8'> {{headerdescription}} <div style='float: right'>{{price}} $</div> </div> <div style=&apos ...

Does JavaScript array filtering and mapping result in a comma between each entry in the array?

The code snippet above showcases a function that retrieves data from a JSON array and appends it onto a webpage inside table elements. //define a function to fetch process status and set icon URL function setServerProcessesServer1761() { var url = "Serv ...

Is there a streamlined approach to signal a successful callback to $q.all without the need to define a $q.defer() variable?

Within my application, I have a mixture of synchronous and asynchronous methods. Here is an example of code from one of the controllers: $q.all([ asyncMethod1(), syncMethod1() ]) .then(function (results) { Even though I don't actually need t ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...

Refresh choices for the user interface selection menu

I've successfully mastered the art of redefining options for Webix ui.richselect/ui.combo. The technique involves: richselect.getList().clearAll(); richselect.getList().parse(options_data) Now, I'm facing a challenge with changing options fo ...

Tips on customizing Google Analytics code with Google Tag Manager

My website is currently equipped with the Google Analytics tracking code implemented through Google Tag Manager. The standard Google Analytics code typically appears as follows: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']= ...

Creating dynamic keys to insert objects

In my coding project, I am dealing with an empty array, a value, and an object. Since there are multiple objects involved, I want to organize them into categories. Here is an example of what I envision: ARRAY KEY OBJECT OBJECT KEY OBJECT ...

Utilize titles and hrefs for images in an array of objects

In my Canvas, there is a map as the background image with markers placed in different cities. These markers are images duplicated from an Array of Objects and added to the Canvas using drawImage(). Now, I need to include href and title attributes in these ...

Accessing node postgres and fetching combined fields with duplicate names

Currently, I am developing a node.js application that utilizes the pg package to connect to a PostgreSQL database. The problem I am encountering involves querying data using a join statement and finding that fields from one table overwrite those from anoth ...

How can PHP information be transmitted to an Ajax response?

I stumbled upon this script online that I'm currently using to identify a visitor's web browser details. This script is triggered when I make an ajax request. At the end of the PHP script, there is an array, return array( 'userA ...

The Power of Symfony Combined with jQuery's Data Handling Function

My app features an ajax navigation system. Each ajax link is given the class ajax, and the page it should load is stored in an aurl attribute, as shown below: <a class="ajax" aurl="/user/posts/3/edit">Edit Post</a> The element's aurl is ...