I wanna extract the text (without any spaces!) between two *
. A sample:
That *is a* simple * demo*. This * will show * my problem.
So. I wanna have the text between the stars. But without any spaces. So if I use matchAll I wish to have the result of:
["is a", "demo", "will show"]
But my regex doesn't remove the empty spaces. Here it is:
var regex = /(\*\s{0,})(\s{0}[\w\s] \s{0})(\s{0,}\*)/ig;
In the end, the first spaces are removed correctly. But the end spaces are not ("will show " as an example).
Greetings, Florian
CodePudding user response:
You have to play with the greediness of quantifiers and target the last character with a character class that excludes spaces and asterisks:
/\*\s*([^*]*[^\s*])\s*\*/
Here [^*]*
matches greedily all the content until the closing asterisk. [^\s*]
forces the last character of the capture group to not be a space character and forces the backtracking (of the previous quantifier) until this one.
CodePudding user response:
let str = "That *is a* simple * demo*. This * will show * my problem.";
let arr = str.match(/\*[^*] \*/g).map(m => m.replace(/\*([^*] )\*/, "$1").trim());
console.log(arr); // ["is a", "demo", "will show"]