如何使用列表作为可能的匹配项来进行regex替换



我有一个要匹配的术语列表,如下所示:

final List _emotions = [
'~~wink~~',
'~~bigsmile~~',
'~~sigh~~',
];

还有第二个替代品列表:

final List _replacements = [
'0.gif',
'1.gif',
'2.gif',
];

这样,如果我有文本:

var text = "I went to the store and got a ~~bigsmile~~";

我可以让它把文本替换为

I went to the store and got a <img src="1.gif" />

因此,从本质上讲,我想在我的text变量上运行regex替换,但搜索模式将基于我的CCD2List。

形成替换文本应该很容易,但我不确定如何使用该列表作为搜索术语的基础

飞镖怎么可能这样?

您需要将两个字符串列表合并到一个单独的Map<String, String>中,该CCD_3将用作字典(确保_emotions字符串使用小写,因为您想要不区分大小写的匹配(,然后将_emotions字符串连接到一个基于交替的模式中。

匹配后,使用String#replaceAllMapped为找到的情绪找到合适的替代品。

注意,如果考虑到~~分隔符,可以缩短模式(请参阅下面的代码片段(。您还可以对词汇表应用更高级的技术,比如regex-trys(请参阅我关于这个主题的YT视频(。

final List<String> _emotions = [
'wink',
'bigsmile',
'sigh',
];
final List<String> _replacements = [
'0.gif',
'1.gif',
'2.gif',
];
Map<String, String> map = Map.fromIterables(_emotions, _replacements);
String text = "I went to the store and got a ~~bigsmile~~";
RegExp regex = RegExp("~~(${_emotions.join('|')})~~", caseSensitive: false);
print(text.replaceAllMapped(regex, (m) => '<img src="${map[m[1]?.toLowerCase()]}" />'));

输出:

I went to the store and got a <img src="1.gif" />

最新更新