I want to use regex to match the string of the following format :(#sometext#)
In the sense ,whatever is there between (# and#) only should be matched.So, the text:
var s = "hello(%npm%)hi";var res = s.split(/(\([^()]*\))/);alert(res[0]);o/p: hello(%npm%)hiAnd
var s = "hello(#npm#)hi";var res = s.split(/(\([^()]*\))/);alert(res[0]);o/p: helloalert(res[1]);o/p : (#npm#);But the thing is , the regex/(\([^()]*\))/ is matching everything between() rather than extracting the string including(# .. #)like:
hello(#npm#)hi- 1You can do something like
s.match(/\(#([^#]*)#\)/)if you don't need the parts outside the parentheses. (Why are you using.split()? If you really want to do that then maybe something likes.split(/(\(#|#\))/)?)nnnnnn– nnnnnn2017-01-09 05:31:13 +00:00CommentedJan 9, 2017 at 5:31 - @nnnnnn: I have edited the questionuser1400915– user14009152017-01-09 05:36:28 +00:00CommentedJan 9, 2017 at 5:36
- Try this:s.match(/((#([^#]*)#))/);user2630764– user26307642017-01-09 05:43:36 +00:00CommentedJan 9, 2017 at 5:43
3 Answers3
By going in your way of fetching content, try this:
var s = "hello(%npm%)hi";var res = s.split(/\(%(.*?)%\)/);alert(res[1]);//o/p: hello(%npm%)hivar s = "hello(#npm#)hi"; var res = s.split(/(\(#.*?#\))/);console.log(res); //hello, (#npm#), hiFrom your comment, updated the second portion, you get your segments in res array:
[ "hello", "(#npm#)", "hi"]1 Comment
The following pattern is going to give the required output:
var s = "hello(#&yu()#$@8#)hi";var res = s.split(/(\(#.*#\))/);console.log(res);"." matches everything between (# and #)
Comments
It depends if you have multiple matches per string.
// like this if there is only 1 match per textvar text = "some text #goes#";var matches = text.match(/#([^#]+)#/);console.log(matches[1]);// like this if there is multiple matches per textvar text2 = "some text #goes# and #here# more";var matches = text2.match(/#[^#]+#/g).map(function (e){ // strip the extra #'s return e.match(/#([^#]+)#/)[1];});console.log(matches);Comments
Explore related questions
See similar questions with these tags.

