Regular expressions: Capturing characters that come after and before a designated symbol

Is there a way to extract all letters, both before and after an underline "_", in JavaScript using Regex while excluding specific words like "pi", "\Delta" and "\Sigma"?

How can this be achieved in Regex JS?

/\b([^e|_|\d|\W])\b/gim /*my regex*/

(1)/(2)+p_a*r*e*t*a*v+pi+\delta+\sigma

(1)/(2)+a_t*e*j*h*o+ \Delta

(1)/(2)+p_w

Answer №1

To exclude the letter e from all lowercase letters a-z, you can utilize a capturing group along with a negated character class:

[_\W]([a-df-z])(?![^_\W])
  • [_\W] This matches an underscore (_) or any non-word character
  • ( Begin capture group 1
    • [a-df-z] Matches lowercase letters a-z excluding e
  • ) End group
  • (?! Negative lookahead to ensure what follows is not
    • [^_\W] Match any character except underscore (_) or non-word characters
  • ) End lookahead

Check out the regex demo here

const regex = /[_\W]([a-df-z])(?![^_\W])/g;
let str = `(1)/(2)+p_a*r*e*t*a*v+pi+\\delta+\\sigma

(1)/(2)+a_t*e*j*h*o+ \\Delta

(1)/(2)+p_w

`;
let m;

while ((m = regex.exec(str)) !== null) {
  // Prevents infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }
  console.log(m[1]);
}

Answer №2

To identify the desired elements, one approach is to use alternation to exclude undesired characters and then capture the desired ones using an expression like:

\\sigma|\\delta|pi|[\W0-9_]|([\w])

The desired letters can be found in capturing group 1:

([\w])

const regex = /\\sigma|\\delta|pi|[\W0-9_]|([\w])/gmi;
const str = `(1)/(2)+p_a*r*e*t*a*v+pi+\\delta+\\sigma

(1)/(2)+a_t*e*j*h*o+ \\Delta

(1)/(2)+p_w`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}


If you want to simplify/adjust/explore the expression further, refer to the explanations provided in the top right section of regex101.com. Additionally, you can see how it matches against sample inputs by visiting this link.


RegEx Circuit

jex.im visualizes regular expressions:

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


Method 2

Alternatively, a custom expression can be crafted based on specific patterns.

[w]|[ate](?=\*)|\b[pa](?=[^a-z])|\b[^(e|_)\d\W]\b

The issue revolves around word boundaries (\b) and underscores since technically underscore falls within the \w character construct.

RegEx Demo 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

Generate a customizable button in Bootstrap using JavaScript extensions

After some investigation on Bugzilla, I discovered that by setting the options URL in install.rdf to arbitrary JavaScript, it can run smoothly. However, a strange issue arises where the window deactivates, as if an invisible dialog has appeared over it, ma ...

Adding a JavaScript widget to a WordPress page

Good morning! I need to place an affiliate external widget on a WordPress page. The code I have loads external content within the page. <script type="text/javascript" src="http://www.convert.co.uk/widget/mobiles.js"></script> The placement o ...

Generate a JavaScript function on the fly

I am looking for a way to dynamically bind a function to the .click() event of multiple divs in a loop. Once clicked, the function should hide the respective div. Despite my attempts, I have been struggling with losing reference to the div and unsuccessful ...

Sorting through a list of strings by checking for a specific character within each string

After spending years dabbling in VBA, I am now delving into Typescript. I currently have an array of binary strings Each string represents a binary number My goal is to filter the array and extract all strings that contain '1' at position X I ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Capture individual frames from angular video footage

Trying to extract frames from a video using Angular has been quite challenging for me. While browsing through Stack Overflow, I came across this helpful post here. I attempted to implement the first solution suggested in the post, but unfortunately, I was ...

Clicking on AngularJS ng-click to navigate to a different page within an Ionic framework application

My goal is to navigate to another page when clicking on a button in the Ionic navbar at the top. However, I am encountering an issue where upon clicking, all nav bar buttons disappear. Interestingly, using dummy codes triggers an alert successfully. But w ...

Trouble with using .className for form validation

The .className is not applying the formValidation class on getWeight.length < 1 and getHeight.length < 1. I am stuck trying to figure out why this is happening after reviewing the code extensively. Any thoughts on what could be causing this issue? Y ...

Tips on including starting information into an angularjs application from the displayed HTML

I'm currently working on a complex AngularJs application that requires User Login. Once the user is authenticated, a page will be displayed to them and additional data will be loaded later. There are two methods for achieving this: XHR Fetch af ...

What specific checks and alerts are triggered by React.StrictMode?

When utilizing React.StrictMode and React.Fragment, according to the React documentation: Both Fragment and StrictMode do not display any visible UI. Instead, they trigger additional checks and warnings for their child components. Question: What specif ...

What causes parameters to be initially passed as undefined when sending them from one component to another, only to later arrive with the actual data intact

When passing properties from a parent component to a child component, my code gets executed before the properties arrive. This results in an error stating "Cannot read properties of undefined (reading 'map')". Why does this occur? https://i.ssta ...

Guide on transitioning from a WebGL renderer to a canvas renderer in three.js

My goal is to display a scene using either a WebGL renderer or a canvas renderer in three.js (version 69). This is the code I am using: <!DOCTYPE html> <html> <head> <script src="./libs/three.js"></script> <scri ...

How to iterate through a Vue data object using forEach loop

I am currently working with a variable in my data: data: function () { return { myVariable: false, } } I'm trying to figure out how to access this variable within a looping function, like the example below: anArray.forEach(functi ...

Is NPM Version Range Syntax More Complex Than Expected?

When specifying required versions of a dependency in npm, ranges of versions can be specified. For instance: 1.2.7 || >=1.2.9 <2.0.0 Specifications can be found here BNF: range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) ...

What methods can I utilize to showcase the JSON data on my webpage efficiently?

I'm currently working on a script that makes an ajax request. The Cloud appears to be responding with JSON data, but I'm not sure how to display this data on my webpage. Any suggestions? Here you can find a link to view the neatly formatted JSON ...

Interactive search tool with multiple fields using HTML and JavaScript

I need help developing a search box for structured data, where I want to implement two types of typeahead searches: one for fields and another for values within those fields. The image below illustrates what I am aiming for. https://i.sstatic.net/MRsJ2.png ...

Disabling 'Input Number' feature is ineffective in Firefox browser

Is there a way to prevent the input value from changing when the up or down arrow is held, even if the input is disabled? I want to retain the arrows without allowing this behavior on Firefox. Give it a try: Press the up arrow. After 5 seconds, the input ...

Using the click function in React to narrow down the component map

Currently, I'm working on an exciting project and I've encountered a bit of a challenge that has me stumped. I'm using Axios to fetch data, then rendering it with a .map function. After that, I have a click function that should display only ...

How can we display a different navbar based on whether the user is logged in or not?

Can anyone share the most effective methods for displaying a different navbar based on whether or not a user is logged in? I have considered a few approaches: One option might involve creating two separate navbars in the HTML file and using CSS to tog ...

Issue with AdminLite 2.4.0 data table functionality malfunctioning

Check out this template that I'm using. I've copied all the contents for the bower_components and dist folders, and made sure to link and require everything properly. There are no 404 errors, only status code 200. Here is a snippet of my code: ...