Home > Net >  How can I do a regex replace using a List as the possible match entires?
How can I do a regex replace using a List as the possible match entires?

Time:02-10

I have a list of terms which I want to match as follows:

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

And a second list of replacements:

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

SO that if I have text:

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

I could have it replace the text as

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

So essentially, I was thinking of running a regex replace on my text variable, but the search pattern would be based on my _emotions List.

Forming the replacement text should be easy, but I'm not sure how I could use the list as the basis for the search terms

How is this possible in dart?

CodePudding user response:

Solved with the help of @Barmar

CodePudding user response:

You need to merge the two string lists into a single Map<String, String> that will serve as a dictionary (make sure the _emotions strings are in lower case since you want a case insensitive matching), and then join the _emotions strings into a single alternation based pattern.

After getting a match, use String#replaceAllMapped to find the right replacement for the found emotion.

Note you can shorten the pattern if you factor in the ~~ delimiters (see code snippet below). You might also apply more advanced techniques for the vocabulary, like regex tries (see my YT video on this topic).

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()]}" />'));

Output:

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