Storing the last encountered bracket type in JavaScript using regular expressions

My JavaScript code needs to match text that meets the following criteria:

  • (surrounded by parentheses)
  • [surrounded by square brackets]
  • not surrounded by either type of bracket

Given the expression...

none[square](round)(accept]able)[wrong).text

... there should be 4 matches for none, [square], (round), and (accept]able). However, [wrong) should not match as it lacks a closing ].

In my attempted regex found at this link...

([([])[A-Za-z]+[\])]|[^\[()\]]+

...issues arose where (accept], able, and [wrong) matched incorrectly. I prioritize correct matching over partial matches with unbalanced brackets.

To improve my regex, I believe I need to adjust the [\])] expression based on the initial matching group, using ) if starting with ( or ] if starting with [.

I've experimented with conditional expressions. While they work in some regex engines like PCRE and Python, I encountered issues when implementing them in JavaScript (see here).

Can this challenge be tackled solely through a JavaScript regex solution, or will it require separate handling in a complex JavaScript function?

Answer №1

To achieve this, one method is to distinguish between two scenarios (acceptable and non-acceptable) and divide the results into two separate capture groups. This way, when working with the results, you simply need to determine which group is successful:

/(\[[^\]]*\]|\([^)]*\)|[a-z]+)|([\[(][\s\S]*?(?:[\])]|$))/gi

Explaining the pattern further:

(  # acceptable capture group
    \[ [^\]]* \]
  |
    \( [^)]* \)
  |
    [a-z]+
)
|
(  # non-acceptable capture group
    [\[(] [\s\S]*? (?: [\])] | $ ) # unclosed parentheses
)

This pattern allows for variations such as a square bracket within round brackets or vice versa. To restrict this behavior and disallow any other types of brackets between them (square or round), use a more specific pattern like this:

(  # acceptable capture group
    \[ [^()\[\]]* \]
  |
    \( [^()\[\]]* \)
  |
    [a-z]+
)
|
(  # non-acceptable capture group
    [\[(] [\s\S]*? (?: [\])] | $ ) # unclosed parentheses
)

Note that with these patterns, you can adjust how unclosed brackets are handled. By default, the non-acceptable part stops at the first closing bracket encountered or at the end of the string if none is found. However, you have the option to modify this behavior so that an unclosed bracket always terminates at the end of the string by using [\[(][\s\S]*$

Answer №2

I'm uncertain if I have captured all potential strings, but perhaps this solution will suffice?

/\[([A-Za-z]*)\]|\(([\]A-Za-z]*)\)/gm

Answer №3

Below is a helpful snippet:

/^(\[[^\[]+?\]|\([^\(]+?\)|[^\[\(]+)$/gm

Check out the DEMO

Answer №4

Here is a solution that should work for you:

\((\w*\s*)\)|\[(\w*)\]|\((\w*\s*|\])*\)|\((\w*\s*|\[)*\)|\[(\w*\s*|\()*\]|\[(\w*\s*|\))*\]|^\b\w*\s*\b

You can see it in action here:

https://regex101.com/r/mV6gD2/2

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

Google Maps autocomplete feature is causing the input to update only after clicking in ng-model

After fetching a Google Maps place ID from a REST API, I utilize the Google Maps API to retrieve the place object in this manner: var geocoder = new google.maps.Geocoder; geocoder.geocode({ 'placeId': data.city }, fun ...

How to merge text (string) with date in HTML using JavaScript

I am attempting to blend a day with the phrase "this is the day" in HTML. I gave it a shot, but the concatenation didn't work as expected. ...

Troubleshooting problems with background-image in CSS using Javascript

My latest project involves coding to assign background images to various classes using jQuery. The image files are named in a numerical order, such as 0bg.jpg, 1bg.jpg, 2bg.jpg, and so on. for (i=0; i < 8; i++) { $('.hpCarousel:eq('+i+' ...

Transform the arrow function into a standard JavaScript function

Here is the React return code snippet I'm working with: return ( <div className='App'> <form onSubmit={this.submit.bind(this)}> <input value={this.state.input} onChange={(e) ...

What is the best way to set a value in PHP that can be utilized as flight plan coordinates on a Google Map within my script?

I am looking to dynamically update the content of my div with id "map" in response to button clicks, where the flight plan coordinates are changing. Currently, I have attempted to achieve this by assigning PHP output to a JavaScript variable as shown below ...

Using React alongside Three.js and OrbitControls across numerous canvases

I've successfully created a React + Three.js sandbox with multiple canvases displaying simple tetrahedron models. However, I am facing an issue where all instances are using Three.OrbitControls in the same way, causing all models to capture mouse even ...

The execution of Node.js on data is triggered only after the content has been successfully written

Hello, I am attempting to establish a connection to a telnet server using Node's net library. const net = require('net'); const con = new net.Socket(); con.connect(23,'10.0.0.120', () => { console.log('Telnet connected ...

Ways to restrict the display or height of a select HTML element

Is there a way to minimize the display or height of a select tag? Here is an image of the desired outcome: I am open to using Javascript, jQuery, CSS, or simply converting it to a list format. I just need guidance on how to achieve this or a sample to re ...

JavaScript conditional array.join operation

I've got an array of strings that I need to display as a comma-separated list, with "and" added before the last element. Here's what I have: const fruits = ["Banana", "Orange", "Apple", "Mango"]; const energy = fruits.join(', ').replac ...

Customizable external URLs in HTML files depending on the environment

Here are the SharePoint URLs for my production, QA, and development environments: Production: QA: Development: I need to adjust relative reference URLs in JS & CSS files (/sites/dev/) for each environment. Is there a way to make this configuration dyna ...

Divide a SINGLE BACKGROUND IMAGE in HTML into two separate links of equal size, one at the top and

As a beginner in HTML, I am trying to find a way to divide a background image into two equal sections without using image mapping. I attempted to split the links by setting the style to 0% and 50% to designate the top and bottom halves, but unfortunately, ...

How can we display a fallback image if the Iframe is unable to load the resource at src in AngularJs?

In one of my JSP pages, I am utilizing an iframe and I want to set an external address as the src of this iframe. Typically, everything works fine. However, in cases where the external source is unavailable, I want to display a static image instead. I&apos ...

Adding a React function to an external object without using React

Here's a simple issue that I'm facing. I am using React Highcharts Official and I want to import graphOptions from another file for the options attribute on ReactHighcharts. <ReactHighcharts highcharts={Highcharts} options={graphOptions} /> ...

Disabling a chosen option within a dropdown menu

`Hello there, I am just starting out with JavaScript and jQuery. Currently, I am developing a web application for ordering food and drinks. I have a dropdown menu for selecting breakfast items and the quantity. When the "add" button is clicked, a dynamic ...

Embed a stackoverflow.com iframe within a jsbin

While exploring code using jsbin, I mistakenly linked the iframe to . When my work in loads, it triggers an alert that redirects back to . I am unable to figure out how to modify my jsbin code. Is there a solution or should I start from scratch? ...

Enhance your color picker with advanced features such as selecting colors directly from your screen

I have created a color picker using react-color () but now I want to add extra functionality. Specifically, I would like the color picker to be able to choose colors from the screen by toggling a feature. I have come across some libraries that claim to off ...

Issue encountered in Meteor/React app: Error message "ReferenceError: require is not defined" or "Error: Cannot

I am currently working on a school project that requires the use of Meteor with React. I have built a website and now I want to include a carousel feature. In order to achieve this, I attempted to utilize the following library: https://github.com/vazco/me ...

What is the best way to eliminate duplicate values from an Array in ReactJS?

Hi there, I'm new to JavaScript and React. I need some help with a project I found on the React blog. I want to try solving it in my own way. This is the content of todoList.js: const todoList = [ {category: 'Sporting Goods', price: &a ...

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...

How can I extract text within a specific HTML tag using Selenium?

On my second day of learning Selenium, I am looking to extract text from within specific HTML tags. Here is a sample of the HTML code: <div id="media-buttons" class="hide-if-no-js"/> <textarea id="DescpRaw" class="ckeditor" name=" ...