Cool12309
Cool12309

Reputation: 171

Do not parse string when using regex

Let's say I have this (in one string):

5: <null>,
6: <null>,
7: 5

I want to remove the lines that contain <null>. My current expression is this:

@"[\d-]" + ": <null>,"

I am pretty sure the reason it is not working is because regex is parsing the 2nd part and I do not want it to. Any help?

Upvotes: 0

Views: 98

Answers (3)

ΩmegaMan
ΩmegaMan

Reputation: 31686

If the data is patterned by numbers (if not I can redo) use that as a pattern to match off of. Here I used named captures to get the key values pairs and put them into a dictionary.

var data = @"5: <null>,
6: <null>,
7: 5";

var dictResult = 
Regex.Matches(data, @"^(?<Key>\d+):\s(?<Value>\d+)", RegexOptions.Multiline)
     .OfType<Match>()
     .ToDictionary (mt => mt.Groups["Key"].Value, mt => mt.Groups["Value"].Value);

     Console.WriteLine (dictResult["7"]); // Prints 5
     Console.WriteLine (dictResult.ContainsKey("5")); // False

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65077

Yes, I am one of those people that doesn't use Regex for everything... so here is a non-Regex version:

var result = input.Split('\n').Where(x => !x.Contains("<null>")).ToArray();

Then perhaps use Join to create a single string afterwards:

var originalWithoutNulls = string.Join("\n", result);

Upvotes: 3

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

Maybe simple Where + Contains/IndexOf instead of RegEx:

string[] lines =...
var filteredLines = lines.Where(line => line.IndexOf("<null>") == -1).ToArray()

Upvotes: 2

Related Questions