createRegexpForPinyinSearch static method

RegExp? createRegexpForPinyinSearch(
  1. String syllable
)

createds a generic regular expression that allows you to search a pinyin regardless of its tone e.g. in a database request

Implementation

static RegExp? createRegexpForPinyinSearch(String syllable) {
  if (syllable.isEmpty) return null;
  syllable = simplifyPinyin(syllable);
  final allVowelsMatch = RegExp('[aouei]+').firstMatch(syllable);
  if (allVowelsMatch != null) {
    final vowels = syllable.substring(
      allVowelsMatch.start,
      allVowelsMatch.end,
    );
    final presplit = vowels.split('');

    String preffix = '^';
    final buffer = StringBuffer('');
    if (allVowelsMatch.start > 0) {
      preffix += syllable.substring(
        0,
        allVowelsMatch.start,
      );
    }
    for (var v in presplit) {
      if (v == 'u') {
        buffer.write('[(?:u|ū|ú|ǔ|ŭ|ù|ü|ǖ|ǘ|ǚ|ǚ|ü̆|ǜ)]');
      } else if (v == 'a') {
        buffer.write('[aāáǎăà]');
      } else if (v == 'o') {
        buffer.write('[oōóǒŏò]');
      } else if (v == 'e') {
        buffer.write('[eēéěĕè]');
      } else if (v == 'i') {
        buffer.write('[iīíǐĭì]');
      }
    }
    if (allVowelsMatch.end < syllable.length) {
      buffer.write(syllable.substring(allVowelsMatch.end));
    }
    buffer.write(r'$');
    final result = '$preffix${buffer.toString()}';
    return RegExp(result);
  }
  return RegExp(syllable);
}