Regular expression ignores the initial "less than" character

Question Statement:

From: John Doe <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb7b2b5b3aeb0b4a9b59dbab0bcb4b1f3beb2b0">[email protected]</a>> Date: Mon, 25 Oct 2021 09:30:15 -0400 Message-ID: <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="276466684e705042405e75640c61621012625d5014665f4e6445694240545052765d1f426b646468171a4f6160546b66674a464e4b09404a464e4b0944484a">[email protected]</a>> Subject: sample subject To: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e4e9e4f5ebeff2eec6ffe7eee9e9a8e5e9eb">[email protected]</a>

In my attempt to use the regular expression:

From:.*<

I noticed that it is overlooking the first < near "[email protected]" and jumping to the following one next to <CAOiWwegy...

What alteration should be made in the regular expression to prevent it from skipping the initial <?

Answer №1

.* 

has a wide range of matches, behaving in a very eager manner.

From:[\sA-Za-z]* 

seems to be the most suitable option for your needs.

alternatively

From:[^<]*

Answer №2

Overview

The pattern you are using, From:.*<, employs the * quantifier which is known as a greedy quantifier. This means that it will match any character any number of times and will continue matching as many characters as possible to satisfy the pattern. In your case, it will match up until the last occurrence of < because of how this greedy quantifier operates.


Code

Here are a couple of methods you can utilize to match up to the first occurrence of < (after From:)

Lazy Quantifier

This method involves making the quantifier * lazy, meaning it will match any character any number of times but only as few as needed. Microsoft's documentation on Backtracking in Regular Expressions explains this concept well:

When a regular expression includes optional quantifiers or alternation constructs, the evaluation of the input string is no longer linear. [...] Therefore, the regular expression engine tries to fully match optional or alternative subexpressions. When it advances to the next language element in the subexpression and the match is unsuccessful, the regular expression engine can abandon a portion of its successful match and return to an earlier saved state in the interest of matching the regular expression as a whole with the input string. This process of returning to a previous saved state to find a match is known as backtracking.

View this regex example here

From:.*?<

Negated Character Set

This method uses a negated character set to match any character except the specified character (in this case, <). It is often considered more efficient than using the lazy quantifier since it does not involve backtracking, resulting in better performance. According to regex101, the Lazy Quantifier method takes 23 steps to match your string while this method requires only 11 steps for the same match.

Check out the regex in action here

From:[^<]*<

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

Having difficulty submitting a form with ajax, while accomplishing the same task effortlessly without ajax

I have been experimenting with submitting a form using ajax to the same .php file. When I submit the form without ajax directly (form action), the database gets updated. However, when I try the same process with ajax, there is no change in the database. H ...

Utilize $http.get within a service/factory to retrieve a set of items

I am trying to utilize a http.get promise within an angularjs service, perform some manipulation on the retrieved collection, and then pass it back to a controller... My query is regarding the proper usage of $http.get() in a service to fetch and modify t ...

Modifying a Nested Component with react-icons

As I work on creating a rating component that utilizes react-icons to display icons, I have encountered an interesting challenge. Currently, I am using the FaStarhalf icon which represents a pre-filled half star that can be flipped to give the appearance o ...

A guide to integrating gatsby-remark-images-grid in markdown with Gatsby.js

Currently, I am working on creating a blog using Gatsby.js with markdown and I want to incorporate CSS grid into my blog posts to showcase a beautiful grid layout of images. I am aware that Gatsby offers incredible plugins to address various challenges. ...

When executing JavaScript code, the file remains unchanged and does not alter the URL

I want my form to check a SQL database upon submission and execute a JavaScript file that captures the data into a constant. However, instead of running the JS script on the page as desired, it redirects to a new URL. Is there a way to ensure that the JS ...

I'm struggling to incorporate MySql tables into my view using EJS. I can't pinpoint the issue

Trying to utilize the data on my EJS page is resulting in the following error: TypeError: C:\Users\ygor\Documents\VS Code\Digital House\PI-DevNap\src\views\user.ejs:22 20| <a class='p ...

The error "marker.setMap not a function" was not caught in the Google Maps API

Currently, I am creating a traffic jam application using MeteorJS 1.4.4.2 + ReactJS. Previously, I have utilized the atmosphere google map package and two popular Google Map npm packages (istarkov and tomchentw), which worked well but did not offer the spe ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

Is it possible to utilize a single command in Discord.js to send multiple embeds?

Is there a way to create a unique bot in Node.js (using Discord.js) by utilizing Visual Studio Code? This exceptional bot should be capable of responding with various embed messages when given one specific command. I attempted using command handler, but u ...

Save the output of a knex query to a variable

I'm struggling to assign the result of a select query using Knexjs to a variable. Here is my code: function getAllCategories() { let categories; categories = database.from("categories").select("category").then(function (rows) { for (let row of ro ...

I'm trying to set an object value for this select element, and while I have managed to do so, I am struggling to display the title of the selected object. Can anyone help me

I am struggling to display the title of the selected object in this select element. Can anyone help me understand why my code is not showing the title? Here is the code snippet: const [selectedCategory, setSelectedCategory] = useState(""); const categor ...

Use AngularJS to extract information from Wikipedia and display it

Just starting out with angularjs and attempting to pull data from Wikipedia to display on the front end. I managed to fetch the data using the php code below: $url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&a ...

Generating a JSON file by combining data from two separate lists in order to render a visually appealing stacked bar chart

Combining two lists to create a JSON for generating a stacked bar chart using JavaScript list1 = ['2019-03-05', '2019-02-20', '2019-02-20', '2019-02-19', '2019-02-18', '2019-02-16', '2019-02 ...

jQuery's load function isn't able to trigger actions on the DOM

Dealing with a straightforward page that dynamically loads content using jQuery's load function to append it to a div. The issue is arising after the loading process, as the jQuery functions I've implemented fail to respond to click events. In a ...

Allow the button to be clicked only when both options from the 1/3 + 1/3 radio buttons are selected

How can I ensure that the next <button> at the bottom of the HTML is only clickable when at least one of each <input type="radio"> is checked? Also, how do I integrate this with my current function? The button itself triggers a jQuery function ...

Building XML using PHP with relatively extensive information stored in JavaScript

Similar Question: XML <-> JSON conversion in Javascript I have a substantial amount of data stored in JavaScript that I need to convert into an XML file on the PHP server. The process of transforming the data into a JSON object, sending it to PH ...

Tips for injecting variables into an .EJS template

On my website, I have an index page, an about page, and a contact page. In addition, there is a header.ejs file that contains the following code: <a href="/">Home</a> | <a href="/about">About Me</a> | <a href="contact">Contac ...

Fluid zooming and panning capabilities when using a logarithmic axis

I'm having trouble with enabling zoom and panning on a Flot plot with a logarithmic x-axis. Every time I attempt to zoom or pan, all the points on the plot disappear and I need to refresh the page. Below is the link to the jsfiddle where I have the f ...

The requested API endpoint for retrieving the name could not be found on the Express

Struggling to configure the restful API for my express app. Below is my app.js code: var express = require('express'), app = express(), bodyParser = require('body-parser'), methodOverride = require('method-override'); rout ...

The reveal/conceal feature will not reveal all elements at the outset

I've been working on implementing a show/hide elements filter. However, I'm facing an issue where all elements that are supposed to display initially are hidden instead. Additionally, the 'active' class is not being properly removed or ...