How do you escape asterisks in Dart?
I have tested the following regular expression on regex101 tester
\*\*(.*?)\*\*
against the following string
find me **this** and **my other string** please
It finds two results ('this' and 'my other string') as expected.
In dart I get a warning in vscode 'use valid regular expression syntax' and it fails with the following error:
FormatException: Nothing to repeat**(.*?)**
I think my asterisks are not being escaped properly. Is there a special way to escape asterisks in dart? Here is a dartpad
https://dartpad.dartlang.org/dbb38b6c97bbc16d994e71e27e9cda30
You can fix this by using raw strings (prefixing the string literal with r
new RegExp(r"\*\*(.*?)\*\*");
or by escaping special characters
new RegExp("\\*\\*(.*?)\\*\\*");
Raw strings can't be used with string interpolation like 'my string $someVar foo'
, because raw means it takes all characters literally.
if text comes from TextField use this:
RegExp.escape();
sample:
RegExp rex = RegExp('${RegExp.escape(searchText)}', caseSensitive: false, unicode: true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With