Alan2
Alan2

Reputation: 24572

How can I remove all instances of a string within a string inside a list?

I have this code:

phraseSources.ToList().ForEach(i => i.JmdictMeaning ?? );

What I need to do, and I'm not it's possible using LINQ, is to remove all occurrences of a string looking like this:

[see=????????]

Note the ??? is meant to indicate there can be any amount of characters, except "]".

That appear inside of JmDictMeaning. Note there might be one or more of these but they will always start with "[see=" and end with "]"

Upvotes: 0

Views: 866

Answers (3)

StepUp
StepUp

Reputation: 38114

You can remove like this:

phraseSources.Select(ph => {ph.JmdictMeaning.Replace("[see=????????]", ""; return ph;})
    .ToList();

Let me show an example:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and query should look like this:

IList<Person> persons = new List<Person>()
{
    new Person(){FirstName = "one1[see=????????]", LastName = "LastName1" },
    new Person(){FirstName = "two1[see=????????]", LastName = "LastName1" },
    new Person(){FirstName = "three1", LastName = "LastName1" },
    new Person(){FirstName = "one[see=????????]", LastName = "LastName1" },
    new Person(){FirstName = "two", LastName = "LastName1" },
};

persons = persons.Select(p => { p.FirstName = p.FirstName.Replace("[see=????????]", ""); 
    return p; })
    .ToList();

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

In order to remove all [see=...] patterns you can try Regex.Replace:

  using System.Text.RegularExpressions;

  ...

  // Add ", RegexOptions.IgnoreCase" if required (if "See", "SEE" should be matched)
  Regex regex = new Regex(@"\[see=[^\]]*\]");

  // "abc[see=456]789" -> "abc789"
  var result = regex.Replace(source, "");

In your case:

  Regex regex = new Regex(@"\[see=[^\]]*\]"); 

  var list = phraseSources.ToList();

  list.ForEach(item => item.JmdictMeaning = regex.Replace(item.JmdictMeaning, ""));

Same idea if you want to filter out items with such strings:

  var result = phraseSources
    .Where(item => !regex.IsMatch(item.JmdictMeaning))
    .ToList();

Upvotes: 1

Danny Goodall
Danny Goodall

Reputation: 838

phraseSources.ToList().RemoveAll(i => i == "xyz");

Yours I imagine would probably look something like

phraseSources.ToList().RemoveAll(i => i.StartsWith("[see=") && i.EndsWith("]"));

Here's an example dotnetfiddle showing it in action

Upvotes: 0

Related Questions