0

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%)hi

And

var s = "hello(#npm#)hi";
var res = s.split(/(\([^()]*\))/);
alert(res[0]);
o/p: hello
alert(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
3
  • 1
    You 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 like s.split(/(\(#|#\))/)?) Commented Jan 9, 2017 at 5:31
  • @nnnnnn: I have edited the question Commented Jan 9, 2017 at 5:36
  • Try this:s.match(/((#([^#]*)#))/); Commented Jan 9, 2017 at 5:43

3 Answers 3

2

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%)hi

var s = "hello(#npm#)hi";
    var res = s.split(/(\(#.*?#\))/);
console.log(res);
    

//hello, (#npm#), hi

From your comment, updated the second portion, you get your segments in res array:

[
  "hello",
  "(#npm#)",
  "hi"
]
Sign up to request clarification or add additional context in comments.

1 Comment

I need the output as : hello, (#npm#), hi for the second example
1

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

0

It depends if you have multiple matches per string.

// like this if there is only 1 match per text
var text = "some text #goes#";
var matches = text.match(/#([^#]+)#/);
console.log(matches[1]);


// like this if there is multiple matches per text
var 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.