-1

I am using regex to remove html tags from my string

Air Receiver <br /> Pressure Washer <br />Vehicle Lift<br />100T Crane Attachment<br />

which is working well.

ViewBag.PlantDetails =
    Regex.Replace(QuoteDetails.PlantDetails, @"<[^>]+>|&nbsp;", " ").Trim();

which returns the following string -

Air Receiver Pressure Washer Vehicle Lift 100T Crane Attachment

My question is, is there a way to add a new line to the string so that it shows like below?

Air Receiver
Pressure Washer
Vehicle Lift
100T Crane Attachment
gunr2171
  • 16,104
  • 25
  • 61
  • 88
ullevi83
  • 199
  • 2
  • 17
  • 5
    Please don't try to parse HTML with regex. Use an HTML parser instead. – gunr2171 Jul 27 '22 at 15:21
  • Your code at the top has nothing to do with the question. – Wiktor Stribiżew Jul 27 '22 at 15:22
  • 2
    _"is there a way to add a new line"_ - yes: Instead of replace by " " replace by [`Environment.NewLine`](https://learn.microsoft.com/en-us/dotnet/api/system.environment.newline?view=net-6.0) – Fildor Jul 27 '22 at 15:25
  • 1
    But to reiterate @gunr2171's point: Only do this if `
    ` will be the only tag you encounter here. If it's html, use html tools.
    – Fildor Jul 27 '22 at 15:27
  • To add to @gunr2171 's comment, see [this very relevant post](https://stackoverflow.com/a/1732454/14868997) – Charlieface Jul 27 '22 at 15:44

1 Answers1

1

So if <br />, and exactly that (with the space and everything) is the only HTML tag that you'll encounter, then Regex is overkill. Use a simple string replace.

var input = "Air Receiver <br /> Pressure Washer <br />Vehicle Lift<br />100T Crane Attachment<br />";
var output = input.Replace("<br />", Environment.NewLine);

In your example, you have spaces sometimes on either end of the break, so trim it if you want.

output = string.Join(Environment.NewLine, output.Split(Environment.NewLine).Select(x => x.Trim()));

If you really want to use Regex, it can be used to match the break and surrounding whitespace.

var output = Regex.Replace(input, @"\s*<br \/>\s*", Environment.NewLine);
gunr2171
  • 16,104
  • 25
  • 61
  • 88