Home > Enterprise >  Regex Expressions in Dart/Flutter
Regex Expressions in Dart/Flutter

Time:11-25

I am developing an app with markdown capabilities, so I am building a lexer to handle this. I am fairly new to Flutter and have little experience with Regex in general.

Essentially there is a difference between *text*, **text**, and ***text***.

My expressions right now are:

r"\B\*[A-Za-z0-9 ] \*\B"
r"\B\*{2}[A-Za-z0-9 ] \*{2}\B"
r"\B\*{3}[A-Za-z0-9 ] \*{3}\B"

The issue is that the first expression is matching the other two. **text*** will get matched also with the second expression. Does anyone know how to solve this?

CodePudding user response:

It looks like you could use:

(?<!\S)(\*{1,3})[A-Za-z0-9 ] \1(?!\S)

See an online demo

  • (?<!\S) - Assert position is not preceded by anything that is not a whitespace char;
  • (\*{1,3}) - Match 1-3 asterisk characters;
  • [A-Za-z0-9 ] - Match 1 characters from given character class;
  • \1 - Backreference what is matched in 1st group;
  • (?!\S) - Assert position is not followed by anything other than whitespace char.

Note that if you'd remove the final negative lookahead you could also match **text** in **test*** if that is what you were after. Or even remove the leading negative lookbehind to match **text** in ****text** test

  • Related