我正在嘗試從 html 字串中洗掉所有鏈接,為此我使用正則運算式將所有<a>標簽替換為<p>. 當標簽被隔離時,正則運算式作業正常,但在字串中間,它不起作用。
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
我期望結果print(html)與print(tag)
uj5u.com熱心網友回復:
將您更改regex為:
const regexString = r'<a href=[a-zA-Z0-9_\W]([^>]*)';
^在你的正則運算式開始時,讓它只檢查字串的開始。
換成你可以試試這個<a>:" "
const regexString = r'<a href=[a-zA-Z0-9_\W]([^>]*)>';
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/530014.html
上一篇:第一百零六篇:變數的不同宣告(var,let和const的不同)
下一篇:一個字串的所有子串,沒有改組
