Reputation: 1943
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
Upvotes: 0
Views: 75
Reputation: 10466
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"
]
Upvotes: 2
Reputation: 622
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 #)
Upvotes: 1
Reputation: 2256
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);
Upvotes: 0