How can I use regex to filter out specific string values?

I am new to the world of regex. I have a string that looks like this:

cn=foo,ou=bar,ou=zoo,ou=aa,ou=bb,ou=cc,ou=dd,o=someOrg,c=UK
. My goal is to extract foo, bar, and zoo from it using JavaScript regex.

const dn = 'cn=foo,ou=bar,ou=zoo,ou=aa,ou=bb,ou=cc,ou=dd,o=someOrg,c=UK';
const regex = /^cn=(\w+),ou=(\w+),ou=(\w+)/;
const found = dn.match(regex);
console.log(found) --> Array ["cn=foo,ou=bar,ou=zoo", "foo", "bar", "zoo"]

Later on, the value of ou=bar needs to be changed based on a new requirement to ou=bar - 1, where the new value may contain a - or a number in any order within the string. I attempted to modify my regex pattern as follows:

const regex = /^cn=(\w+),ou=(.+),ou=(\w+)/;

Unfortunately, this regex returned unwanted data:

Array ["cn=foo,ou=bar,ou=zoo,ou=aa,ou=bb,ou=cc,ou=dd", "foo", "bar,ou=zoo,ou=aa,ou=bb,ou=cc", "dd"]

What I actually want is:

Array ["cn=foo,ou=bar - 1,ou=zoo", "foo", "bar - 1", "zoo"]
. I tried to exclude the unwanted data by using
^(ou=aa|ou=bb|ou=cc|ou=dd|o=someOrg|c=UK)
within the regex, but ended up with a null value. Any help with correcting the regex syntax would be greatly appreciated.

Update:

I experimented with

/^cn=(\w+),ou=(\w+\s+-\s+\d+),ou=(\w+)/
which works for the previous example but doesn't cover cases like ou=bar-1 or ou=1bar-...

Answer №1

A simple solution for this problem is to use a non-greedy approach, indicated by adding a question mark:

const pattern = /^cn=(\w+),ou=(.+?),ou=(\w+)/;

Another option is to adjust the regex to exclude commas:

const pattern = /^cn=(\w+),ou=([^,]+),ou=(\w+)/;

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 JSON request object has not been defined

I am currently facing an issue while trying to make a JSON request from the open weather API example. When I attempt to access the key value in the $.each method, it keeps showing that the value for the key is undefined. Can someone please review the code ...

Utilizing jQuery, Ajax, and PHP to Transfer Both FormData and String Data

I want to pass a FormData value and some String values to a PHP page. Below is my JavaScript code: $.ajax({ url: 'upload-pic.php', type: 'post', data: { type : type, ...

An effective approach to positioning HTML elements at specific X and Y coordinates

I have an innovative project idea! The concept is to enable users to create points by clicking on the display. They can then connect these points by clicking again. However, I am facing a challenge when it comes to creating HTML elements at the exact loc ...

Tips for maintaining UV mapping integrity while updating map textures

I have a GLTF model that needs its map texture updated, but when I do so, the new texture displays without preserving the UV mapping of the model. Is there a method to maintain the UV mapping when loading a new texture? Below is the snippet of code I util ...

Many inhabitants - utilizing mongoosejs

Just a simple question, for example with a double reference in the model. Schema / Model var OrderSchema = new Schema({ user: { type : Schema.Types.ObjectId, ref : 'User', required: true }, meal: { ...

The identical page content is displayed on each and every URL

Implementing a multi-step form in Next JS involves adding specific code within the app.js file. Here is an example of how it can be done: import React from "react"; import ReactDOM from "react-dom"; // Other necessary imports... // Add ...

Unable to retrieve nested element from its parent

I am facing an issue with accessing a child element's method from the parent element using ref='menu'. When I try to call $refs.menu.show in a button element within the Vue app, it works fine. However, when I try to do the same in a photo el ...

Why is it that in React the render method is automatically bound to the component instance, while custom methods are not provided

Why is the render method automatically bound to the component instance in a class, but custom methods such as event handlers are not? I realize that using the bind keyword can make these event handlers work, but I'm curious to know why "this" can be ...

Passport appears to be experiencing amnesia when it comes to remembering the user

After extensive research online, I have yet to find a solution to my issue. Therefore, I am reaching out here for assistance. I am currently working on implementing sessions with Passport. The registration and login functionalities are functioning properl ...

The task was unsuccessful as Travis encountered a status code of 127

I'm currently using Travis for the project build process. My deploy script is as follows: deploy: provider: script script: - npm run deploy - npm run test:deploy-results skip-cleanup: true on: branch: build Below is the npm scrip ...

Mongoose fails to persist data

Exploring the world of Express and following a tutorial to create a project. Currently stuck in the seeding phase where I am trying to populate my database with data. However, when I execute the command node product-seeder.js in the terminal, no data is be ...

Electron triggers MouseLeave event on child elements

Dealing with mouse hover events can be a bit tricky, especially when working with AngularJS in an Electron-hosted app. Here's the HTML template and script I'm using: HTML: <div id="controlArea" (mouseenter) = "onControlAreaEnter()" ...

Add transparency to the background color when hovering over inline elements

Initially, my style sheet had the following structure: .button { border-radius: 3px; display: inline-block; padding: 14px 20px; transition: background-color cubic-bezier(0.4, 0.0, 0.2, 1.0) 300ms; &:hover { background-color: transparent ...

"Comet Error: Trouble in the World of Javascript

Currently, I have Orbited set up as a Comet server on my localhost. It's actively listening to the following ports: 9000 for http 61613 for stomp While troubleshooting, my JavaScript debugger is pointing out an error message: JSON is not defined spe ...

When attempting to register a custom Gamepad class using GamepadEvent, the conversion of the value to 'Gamepad' has failed

I have been working on developing a virtual controller in the form of a Gamepad class and registering it. Currently, my implementation is essentially a duplicate of the existing Gamepad class: class CustomController { readonly axes: ReadonlyArray<nu ...

Dynamic image updates in real-time

Beginning a new project and already facing a roadblock, I could really use some assistance. I have 16 (4x4) images that I am displaying on a page. $max_images = $_GET['images']; $num_images = $max_images; while (($num_images > 0) && ...

Navigate within a div using arrow keys to reposition another div

As a newcomer to JavaScript, I am facing some challenges. My goal is to use arrow keys to move a small div inside a larger div. However, the code below is not functioning as expected. Here is the HTML and CSS: <div id="rectangle"> <div id="s ...

Transfer a value to the ng2 smart table plugin extension

Upon reviewing the document and source code related to pagination implementation in the (advanced-example-server.component.ts), I discovered that the ServerDataSource being used only supported pagination through HTTP GET (_sort, _limit, _page, etc paramete ...

Utilizing the TypeScript compiler through an NPM module command

I am currently working on a project written in TypeScript and utilizing a task runner for building purposes (such as Gulp, Jake, etc.). The TypeScript compiler that I am using has been installed from NPM through the following command: npm install typescri ...

Extract all objects from an array where a specific field contains an array

data:[ { id:1, tags:['TagA','TagB','TagC'] }, { id:2, tags:['TagB','TagD'] }, { id:3, tags:[&a ...