0

How should we replace <br /> html tags with line feed '\n' using RegExp in dart?

Input:

one<br />two<br />three

Output:

one
two
three
5
  • Why do you need a regular expression? A simple search-and-replace action seems to be sufficient. Unless you need to handle variable amounts of whitespace, then <br\s*/> would be a useful search regex. Commented Jul 13, 2022 at 13:49
  • text can contain <br/> or <br /> Commented Jul 13, 2022 at 13:55
  • As I wrote, then <br\s*/> should work. Commented Jul 13, 2022 at 14:04
  • no, its not working Commented Jul 13, 2022 at 14:04
  • What syntax are you using to construct the regex in Dart? Commented Jul 13, 2022 at 14:07

1 Answer 1

1
final _brRe = RegExp(r"<br\s*/>");
String replaceBreaks(String input) =>
    input.replaceAll(_brRe, "\n");

You create a RegExp using the RegExp constructor, remembering to always use a raw string literal, so you don't need to double-escape backslashes.

Then you just use String.replaceAll to replace all substrings matched by the RegExp with a newline.

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

2 Comments

With this, problem is middle one is getting missed out.... Input: One<br />two<br />three. Output: one\nthree
When I run the code, it correctly replaces both <br />s with newlines, and retains the One, two and three strings. Check: dartpad.dev/?id=a6b1cb1898e0aaa38ddb78a226790a34 . You must be doing something differently. Are you, by any chance, changing the regexp to r"<br.*/>"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.