CSharpNewBee
CSharpNewBee

Reputation: 1981

retain the newline in a regex Match, c#

So, i've created the following regex which captures everything i need from my string:

  const string tag = ":59";
  var result = Regex.Split(message, String.Format(":{0}[^:]?:*[^:]*", tag),RegexOptions.Multiline);

the string follows this patter:

:59A:/sometext\n
somemore text\n
:71A:somemore text

I'm trying to capture everything in between :59A: and :71A: - this isn't fixed in stone though, as :71A: could be something else. hence, why i was using [^:]

EDIT

So, just to be clear on my requirements. I have a file(string) which is passed into a C# method, which should return only those values specified in the parameter tag. For instance, if the file(string) contains the following tags:

:20: :21: :59A: :71A:

and i pass in 59 then i only need to return everything in between the start of tag :59A: and the start of the next tag, which in this instance is :71A:, but could be something else.

Upvotes: 2

Views: 106

Answers (1)

Szymon
Szymon

Reputation: 43023

You can use the following code to match what you need:

string input = ":59A:/sometext\nsomemore text\n:71A:somemore text";
string pattern = "(?<=:[^:]+:)[^:]+\n";

var m = Regex.Match(input, pattern, RegexOptions.Singleline).Value;

If you want to use your tag constant, you can use this code

const string tag = ":59";
string input = ":59A:/sometext\nsomemore text\n:71A:somemore text";
string pattern = String.Format("(?<={0}[^:]*:)[^:]+\n", tag);

var m = Regex.Match(input, pattern, RegexOptions.Singleline).Value;

Upvotes: 2

Related Questions