Reputation: 65
I searched and searched, but I just can't seem to find the correct answer, so I'm asking it here (regexp newbie).
I'm trying to extract the value include this between the following:
[tag1]include this [tag1]
I only want to get the value "include this" as an result. To make this more complex, the regex needs to look at the value tag1, because I got more than one of those brackets in the same body. To top it: the tekst on multiple lines has to be included.
So far, I tried the following single line regexp (can only use single line regexp):
(?!\[?.*\]).*(?=\{\/?.*\})
and
(\[[^\]]+\](?!\s)([\w']+)(?!\])\b|(?:^|\s)([\w']+)(?!\])\b)
These two both seem to do the trick for the first part (extract only the text "include this" between the tags, but he doesn't look at the part [tag1]. So in short: i'm looking for a regexp which can extract the value "include this" while looking at the inside of the brackets, the "tag1".
I'm feeling real close, but now i'm stuck.
Please help?
Upvotes: 2
Views: 682
Reputation: 834
If you want all text between two "tag1" tags do this
(?<=\[tag1\])(.|\r|\n)*?(?=\[/?tag1\])
If you want all text between matching tags do this
(?<=\[([a-z0-9]+)\])(.|\r|\n)*?(?=\[/?\2\])
Upvotes: 1
Reputation: 17453
Or don't use regexp, which is what I usually do when the regexp "won't behave"[1] and what you're doing is pretty straight forward. (I realize your question explicitly asked for regexp, but hopefully this is potentially helpful.)
function parseTags(str)
{
var indexNext,
arrayOut = [];
while (str.indexOf("[tag1]") >= 0)
{
str = str.substring(str.indexOf("[tag1]") + 6);
// What do you want to do if a tag's missing?
// Skipping the end tag-less "match" for now.
indexNext = str.indexOf("[tag1]");
if (indexNext >= 0)
{
arrayOut.push(str.substring(0, indexNext));
str = str.substring(indexNext + 6);
}
// Alternately, could `break` on else and save a trip.
}
return arrayOut;
}
[1] Yes, I realize that's my failure when the regexp "won't behave". ;^)
Upvotes: 0
Reputation: 13534
You may able to do it without Regex by creating a function takes the tag and the string as parameters, like the following:
function extractText(tag, str){
tL = tag.length; //tag length
tP = str.indexOf(tag); // position of tag
sT = str.substr((tP+tL)); //remaining string after tag
cT = sT.indexOf(tag); //closing tag position
return sT.substring(0,cT)
}
<a href="javascript:alert(extractText('[tag1]','[tag1] include this [tag1]'))">Test</a>
A live demo is here
Upvotes: 0
Reputation: 2398
This will match two matching tags and extract the middle.
\[([^\]]+)\]([^\[]+)\[\1\]
$1 backreference will get your tag ("tag1" in your example), and $2 will pull out the inner text.
Upvotes: 1
Reputation: 67968
\[tag1\]((?:(?!\[tag1\]).)+)
Try this.See demo.Grab the capture.
http://regex101.com/r/yW4aZ3/117
Upvotes: 1