Home > OS >  How to write a Reg Expression of a string that contains two tilde ~ , or two underscore
How to write a Reg Expression of a string that contains two tilde ~ , or two underscore

Time:12-07

Asterisk is working well. But I haven't figured out how to write an expression for underscore and tilde... I have tried multiple combinations. Please ignore what you see on the code below.

   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 ' ';
        });
      } 

CodePudding user response:

Here is a regex that will have a match if you either have _ some text _, *some text* or ~some text~, hopefully that solves your issue:

([_~*]).*?\1

of course, it also matches __, ~~ and **

Here is the Debuggex Demo

CodePudding user response:

this is a function that returns a TextSpan based on input 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);
}

you can test it by calling:

final span = rich('some _italic_ word, some in *bold* and ~lineThrough~ works too');

  • Related