Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to select text without white spaces with restrictions

I need to select some text between % signs where there is not white space between 2 %.

This should match:

%link%

This shouldn't:

%my link%

This easy regex would do the trick:

/%\S*%/g

But there is a catch: I can add a prefix: % and a suffix: % but the regex must contain this between these: (.+?) (it's a third party script).

So this is the regex I need to adjust:

/%(.+?)%/

Because of "(.+?)" I need a workaround, any idea?

UPDATE: All of these are true for a perfect regex:

regex = /%(.+?)%/g // default regex which allows spaces so it's not good

regex.test('%link%')
regex.test('%my link%') === false
regex.toString().includes('(.+?)')
like image 258
AllainLG Avatar asked Dec 07 '25 08:12

AllainLG


1 Answers

You can use

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

See the regex demo.

Details:

  • % - a % char
  • (?=[^\s%]+%) - a positive lookahead that requires any one or more chars other than whitespace and % immediately to the right of the current location
  • (.+?) - Group 1: any one or more chars other than line break chars
  • % - a% char.

See a JavaScript demo:

const some_hardcoded_value = ".+?";
const regex = new RegExp("%(?=[^\\s%]+%)(" + some_hardcoded_value + ")%", "g");
const str = "%link% This shouldn't %my link%  %%link,,,,,%%%%";
console.log(Array.from(str.matchAll(regex), x => x[1]));
like image 199
Wiktor Stribiżew Avatar answered Dec 08 '25 22:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!