星號運行良好。但是我還沒有弄清楚如何為下劃線和波浪號撰寫運算式......我嘗試了多種組合。請忽略您在下面的代碼中看到的內容。
else if (message.text.contains("_")) {
message.text.trim().splitMapJoin(RegExp(r'/_(._?)_/'), onMatch: (m) {
textParts.add(TextSpan(
text: m.group(1), style: TextStyle(fontStyle: FontStyle.italic)));
return '';
}, onNonMatch: (String text) {
textParts.add(TextSpan(text: text));
return ' ';
});
}
else if (message.text.contains("*")) {
message.text.trim().splitMapJoin(RegExp(r'\*(.*?)\*'), onMatch: (m) {
textParts.add(TextSpan(
text: m.group(1), style: TextStyle(fontWeight: FontWeight.bold)));
return '';
}, onNonMatch: (String text) {
textParts.add(TextSpan(text: text));
return ' ';
});
}
else if (message.text.contains("~")) {
message.text.trim().splitMapJoin(RegExp(r'\~(.~?)\~'), onMatch: (m) {
textParts.add(TextSpan(
text: m.group(1), style: TextStyle(decoration: TextDecoration.lineThrough)));
return '';
}, onNonMatch: (String text) {
textParts.add(TextSpan(text: text));
return ' ';
});
}
uj5u.com熱心網友回復:
這是一個正則運算式,如果您有_ some text _,*some text*或~some text~,它將匹配,希望可以解決您的問題:
([_~*]).*?\1
當然,它也匹配__,~~并且**
這是Debuggex 演示
uj5u.com熱心網友回復:
這是一個TextSpan基于輸入回傳 a 的函式String:
TextSpan rich(String input) {
final styles = {
'_': const TextStyle(fontStyle: FontStyle.italic),
'*': const TextStyle(fontWeight: FontWeight.bold),
'~': const TextStyle(decoration: TextDecoration.lineThrough),
};
final spans = <TextSpan>[];
input.trim().splitMapJoin(RegExp(r'([_*~])(.*)?\1'), onMatch: (m) {
spans.add(TextSpan(text: m.group(2), style: styles[m.group(1)]));
return '';
}, onNonMatch: (String text) {
spans.add(TextSpan(text: text));
return '';
});
return TextSpan(style: const TextStyle(fontSize: 24), children: spans);
}
您可以通過呼叫來測驗它:
final span = rich('some _italic_ word, some in *bold* and ~lineThrough~ works too');
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374046.html
上一篇:除以零飛鏢顫動時的計算器驗證
