get some char between two spacial char without space with regex

Viewed 55

for example : i wanna get *created by:* and *M* and don't get *proudly * or * proudly*(have space near * or * ) with regex in javascript.

//not work
let c = "RegExr was *created by:* gskinner.com, and is *proudly *hosted by *M*edia Temple.";
const regExr = /(\*\*)([^\s|\*])+([^\s|\*])(\*\*)/g;

this work ( tnx for @Wiktor Stribiżew )

const regExr = /\*([^*]*[^*\s])\*/g;

but not working for : * proudly*

i changed to -> /\*([^*\s]*[^*\s])\*/g

but don't get -> *created by:*

2 Answers

First, match all result that is in between * and then filter the result that doesn't contain space before last (*)

let c ="RegExr was *created by:* gskinner.com, and is *proudly *hosted by *M*edia Temple.";
const regExr = /(\*)(.+?)\1/g;

const result = c.match(regExr).filter((el) => !el.match(/\*.+\s\*/));

console.log(result);

You can use

let c = "RegExr was *created by:* gskinner.com, and is *proudly *hosted by *M*edia Temple. And * proudly* presents...";
const regExr = /\*([^\s*](?:[^*]*[^*\s])?)\*/g;
// Getting all matches with asterisks
console.log(c.match(regExr));
// Or, only the contents between
console.log(Array.from(c.matchAll(regExr), x=>x[1]));

See the regex demo.

Details

  • \* - a * char
  • ([^\s*](?:[^*]*[^*\s])?) - Group 1: any one char other than whitespace and asterisk, then an optional occurrence of zero or more chars other than * and then a char other than whitespace and *
  • \* - a * char.

A variation of a two-step approach that should be a bit more versatile than the above one-step approach (especially in case of unbalanced amount of asterisks):

let c = "RegExr was *created by:* gskinner.com, and is *proudly *hosted by *M*edia Temple.";
const regExr = /\*([^*]*)\*/g;
console.log(c.match(regExr).filter( x => !/\s\*$/.test(x)) )
console.log(Array.from(c.matchAll(regExr), x=>x[1]).filter(x => x == x.trim()) )

Related