Click here to Skip to main content
15,910,471 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to extract data between two know strings.
pattern 1 = [[
pattern 2 = ]]

I want data between first occurrence of the pattern1 and last occurrence of pattern2

Data = [[jhsa,dgvfjhvfhl[[ks,dbfvhbf]]jmsaefvkjhera]]mhsdgvgcvds[[MSNDvcgsdv h]]<JSVDjhgs]]

My Output : MSNDvcgsdv h]]<JSVDjhgs]]


Expected Output : [[jhsa,dgvfjhvfhl[[ks,dbfvhbf]]jmsaefvkjhera]]mhsdgvgcvds[[MSNDvcgsdv h]]<JSVDjhgs


please help me with this.

Thanks in advance

What I have tried:

var Datamsg = Regex.Match(Data, @"\[\[(.*)\]\]", RegexOptions.RightToLeft).Groups[1].Value;
Posted
Updated 10-May-18 11:41am
v5

The problem is the .*? in your regex: the ? means "lazy" and will cause the regex to stop at the first ]] it comes across, but you want the last.

Remove the question mark (so replace .*? by .*), this will make the regex "greedy" and consume as much as possible.
 
Share this answer
 
Comments
BillWoodruff 10-May-18 19:51pm    
+5
I appreciate RegEx; in this case, it's pretty simple to use String methods:
const string twoOpenBrackets = "[[";
const string twoCloseBrackets = "]]";

// in some method:

int ndx = data.IndexOf(twoOpenBrackets);

if(ndx < 0 || data == String.Empty) throw new ArgumentException("no [[");

data = data.Substring(ndx);

ndx = data.LastIndexOf(twoCloseBrackets);

if (ndx < 2) throw new ArgumentException("no ]]");

data = data.Substring(0, ndx);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900