Reputation: 247
The closes I got is this _(.*?)_
What regex should I use to get every instance of string in between underscores but should not be a substring of a string (check test3) and should not also get those in new line (check test4)
var string = "_test1 test2_ test_3_ _\n test4_ _test5_"
The regex should only get _test1 test2_
& _test5_
Note: any character/string the word test doesn't matter
Upvotes: 0
Views: 941
Reputation: 11032
You can use this regex
(?:^| )(_(?:[\w ]+?)_|([*~])(?:[\w ]+?)\2)(?= |$)
JS Demo
var re = /(?:^| )(_(?:[\w ]+?)_|([*~])(?:[\w ]+?)\2)(?= |$)/g;
var str = "_test1 test2_ test_3_ _\n test4_ *test5* test*3* _asdf_ _ghjkl_ _mno_";
document.writeln("<pre>" + str.match(re) + "</br>" + "</pre>");
Upvotes: 2
Reputation: 5891
If you can guarantee that each underscore pair is separated by a whitespace character (so no two underscores are next to one another), then this regex will work: \b_([\w\s]+?)_\b
To match any of the 3 cases you need, use this regex: (?:\b|\s|^)[_*~]([\w\s]+?)[_*~](?:\s|$)
Upvotes: 2
Reputation: 7026
For getting the required value from
test1 test2 test_3_ \n test4 test5
use
_test[^_\n]+_
The below one works as well.
^_([^_]+?)_|_([^_]+?)_$
text.match(/^_([^_]+?)_|_([^_]+?)_$/g);
Upvotes: 1