Unspeakable
Unspeakable

Reputation: 247

Regex that match strings in between underscores, asterisks & tilde

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

Answers (3)

rock321987
rock321987

Reputation: 11032

You can use this regex

(?:^| )(_(?:[\w ]+?)_|([*~])(?:[\w ]+?)\2)(?= |$)

Regex Demo

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

Steven Lambert
Steven Lambert

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

Krishna Thota
Krishna Thota

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);

http://regexr.com/3df3m

Upvotes: 1

Related Questions