Searching for patterns in text to identify non-blank characters with specified limitations

I'm looking to extract text surrounded by % symbols without any whitespace between them.

For example, this should match:

%link%

But this shouldn't:

%my link%

An easy regex solution would be:

/%\S*%/g

However, there's a requirement to include a prefix: % and a suffix: % in the regex pattern but keep it within these brackets: (.+?) (which is mandated by a third-party script).

So I need to modify the regex as follows:

/%(.+?)%/

Due to the limitation of "(.+?)", I need a workaround. Any suggestions?

UPDATE: The ideal regex should meet the following criteria:

regex = /%(.+?)%/g // default regex allowing spaces (needs improvement)

regex.test('%link%')
regex.test('%my link%') === false
regex.toString().includes('(.+?)')

Answer №1

Utilize the following code snippet:

var some_value = ".+?";
var regex = new RegExp("%(?=[^\\s%]+%)" + some_value + "%", "g");

For a demonstration, check out the regex demo here.

Specifics:

  • % - represents a % character
  • (?=[^\s%]+%) - a positive lookahead that necessitates any number of characters excluding spaces and % right after the current position
  • (.+?) - Group 1: denotes any sequence of characters except line breaks
  • % - signifies a % character.

Review a JavaScript demo below:

const some_value = ".+?";
const regex = new RegExp("%(?=[^\\s%]+%)(" + some_value + ")%", "g");
const str = "%link% Ignore this %my link%  %%link,,,,,%%%%";
console.log(Array.from(str.matchAll(regex), x => x[1]));

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

What is the process for importing a sprite sheet along with its JSON file into my Phaser game?

Currently, I am in the process of developing a game using the powerful phaser game engine. To enhance the visual appeal of my game, I decided to create a sprite sheet and successfully downloaded it. The sprite sheet consists of a 256 × 384 .png file ...

Generate a random word using Typed.js

Can Typed.js generate a random word for output? $(function(){ $(".element").typed({ strings: ["Lorem", "Ipsum", "Dolor"], typeSpeed: 0 }); }); The output should be one of the following words. (Lorem / Ipsum / Dolor) ...

Verify if the value in a textbox exceeds the number entered in an array of textboxes

My goal is to compare the value of a single text box, labeled as "totalmarkstoall", with multiple arrays of text boxes labeled as "marksscored". The JavaScript code below is set up to compare these values using a key up function. The issue I am facing is ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...

What are some ways to customize the appearance of the Material UI table header?

How can I customize the appearance of Material's UI table header? Perhaps by adding classes using useStyle. <TableHead > <TableRow > <TableCell hover>Dessert (100g serving)</TableCell> ...

Jest-Native encountered an error: "SyntaxError: Unable to use import statement outside of a module"

Trying to perform unit testing using https://github.com/callstack/react-native-testing-library along with https://github.com/testing-library/jest-native. I am able to test plain JavaScript files without any issues, but I am facing an error when testing com ...

Why is the $scope variable value not being updated in Angular JS controller?

My controller code snippet is shown below. I am trying to access the value of $scope.FCGId. How can I access this variable? angular.module('hotelApp.controllers') .controller('menuCtrl', ['$scope','menu' ...

How can I replicate a div in Angular 6 using typescript?

I'm currently working on a project focused on providing detailed information about various vehicle components. Each component consists of specific descriptive fields. One feature I'm looking to implement is an "Add another component" button that ...

Calendar display - Days grouped on the left side, with the times arranged across the top in week view?

I'm curious whether it's feasible to display a comprehensive calendar view featuring the days on the left side for the week and the times across the top. Can such a layout be achieved? https://i.sstatic.net/SFtmG.png ...

Exploring Manipulation of M:N Associations in Sequelize

I have set up a sequelize schema using postgre DB export const Commune = sq.define("commune",{ codeCommune: { type: DataTypes.STRING(5), allowNull: false, primaryKey: true }, libelleCommune: { type: ...

Why is my npm installation generating an ERESOLVE error specifically linked to karma-jasmine-html-reporter?

Could someone help me understand this dependency error I encountered while running npm install and provide guidance on how to resolve such errors? View Error Screenshot I am currently using Angular 16, the latest stable version. npm ERR! code ERESOLVE ...

Creating texture using an array in three.js

I've been experimenting with generating textures from arrays in threeJS but I'm encountering unexpected results. It seems like the method I'm using to generate the texture is incorrect. When I use the texture from the following link, every ...

Retrieve a list of IDs specifically for the array objects that have been modified in Mongodb

In this instance, I am showcasing a snippet from my "messages" collection. {[ _id: xxx, shipment: { _id: xxx }, messages: [ { _id: 123, origin: 'driver' isRead: false, ... }, { _id: 234, ...

Generating JSON Data with the Power of JavaScript and JQuery

Looking to dynamically generate a JSON Object with the specified structure: { "deleteId":[1,2,3], "pointId":[1,2,3], "update":[ { "what":"mission", "id":1, "value":"adsda" }, { ...

Learn how to dynamically change a class name with JavaScript to alter the color of a navbar icon

I have little experience with javascript, but I want to make a change to my navbar icon. Currently, my navbar has a black background with a white navbar icon. As I scroll the page, the navbar background changes to white and the font color changes to black. ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

Learning to transform EST time data into local time within JavaScript utilizing moment.js and Date objects

The recorded date and time is "03/19/2020 13:15:00" in Eastern Standard Time (EST). When attempting to convert it to the local timezone, I have tried various methods, such as using moment.js to change the format from 'MM/DD/YYYY HH:mm:ss' to UT ...

Execute a function when the button is clicked

Currently in the process of learning HTML and Javascript. I was able to search online for information on how to navigate to a URL and extract a value from returned JSONP. However, the function is executing when I load the HTML page, and I would prefer it t ...

Add fresh material to the bottom of the page using Javascript

Hey there, I'm having a bit of trouble with my page where users can post their status. I want the new posts to appear at the bottom after the older posts when the user presses the button. Currently, Ajax is placing all new posts at the top of the old ...

Anticipating the need for a recursive function to call another async function repeatedly

My current function implementation looks like this: function populateMap(directory: string, map, StringMap) { fs.promises.readdir(directory).then(files: string[]) => { files.forEach(file: string) => { const fullPath = path.jo ...