1

I have some text of which the following is a sample:

  2_Chief Ships.Niobe 2 0 2 1.0
  3_Chief Vehicles.WillisMB_US 1
[0_Chief_Road]
  77704.27 140254.33 120.00 0 2 9.166666984558105
  100653.84 140379.05 120.00
[2_Chief_Road]
  76911.77 139996.94 120.00 0 2 3.8583335876464844
  100446.47 140028.61 120.00

I want to retrieve this part under [0_Chief_Road]:

77704.27 140254.33 120.00 0 2 9.166666984558105
100653.84 140379.05 120.00

I'm using this code:

System.Text.RegularExpressions.Regex reg = null;
string routeTitle = "[0_Chief_Road]";  //  this is hard coded for StackOverflow
reg = new System.Text.RegularExpressions.Regex(@"(?<=" + routeTitle + @")[\d\.\s]+(?=\[)");
string routeText = reg.Match(chiefsSection).Captures[0].ToString();

The result I'm getting is:

4.27 140254.33 120.00 0 2 9.166666984558105
  100653.84 140379.05 120.00

...which is everything after the first zero! I've tried changing the values and it always returns everything after the first zero. I don't get why!!

Can anyone help out here? Thank you!

Gregg

1 Answer 1

2

The problem is that routeTitle contains brackets that, when used in a regular expression, will be interpreted as a character class. You need to escape any literal string before inserting it into a regular expression.

So you should use string routeTitle = @"\[0_Chief_Road\]";

Or use the Regex.Escape() function:

string routeTitle = "[0_Chief_Road]";  //  this is hard coded for StackOverflow
reg = new System.Text.RegularExpressions.Regex(@"(?<=" + Regex.Escape(routeTitle) + @")[\d\.\s]+(?=\[)");

Be aware that the CRLF after [0_Chief_Road] will also be part of the match - if you don't want that, add a \s+ at the end of the lookbehind assertion.

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that's it. Thanks for waking me up!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.