const regex = /(?<=(?:\s|^)(?![@#])(?!__)\S*)_([^_]+)_/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?<=(?:\\s|^)(?![@#])(?!__)\\S*)_([^_]+)_', 'gm')
const str = `Test sentence:
_some_val #ta_g_ and _some_ value, but some_val_ and #some_tag_value and @a_mention_ and a #_tag_
Should match (between underscores)
----
_italic text here_
police_woman_
_fire_fighter
a thousand _words_
_brunch_ on a Sunday
match_this_and_that_
Should not match anything
----
@ta_g_
__value__
#some_tag_value
@some_value_here
@some_tag_
#some_val_
#_hello_
@match_this_and_that_`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions