Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dart – Replacing regex match in the middle of String

I’m trying to remove all links from a html string and to do so I’m using a regex to replace all <a> tags by <p>. The regex works fine when the tag is isolated, but in the middle of the string, it doesn’t work.

String tag = '<a href=\"https://www.google.com/\" target=\"_blank\" rel=\"noopener\">word</a>';
String html = 'regex with a <a href=\"https://www.google.com/\" target=\"_blank\" rel=\"noopener\">word</a> in the middle';

const regexString = r'^<a href=[a-zA-Z0-9_\W]([^>]*)';
final regex = RegExp(regexString);

html = html.replaceAll(regex, '<p').replaceAll('</a>', '</p>');
tag = tag.replaceAll(regex, '<p').replaceAll('</a>', '</p>');
  
print(tag); //<p>word</p>
print(html); //regex with a <a href="https://www.google.com/" target="_blank" rel="noopener">word</p> in the middle

I’m expecting the result of print(html) to be the same as print(tag)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Change your regex to this:

const regexString = r'<a href=[a-zA-Z0-9_\W]([^>]*)';

^ at the start of your regex make it to check only start of string.

for replacing <a> with " " you can try this:

const regexString = r'<a href=[a-zA-Z0-9_\W]([^>]*)>';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading