Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression, how to escape characters, specifically an asterisk

Tags:

dart

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

like image 655
atreeon Avatar asked Jan 02 '23 09:01

atreeon


2 Answers

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.

like image 90
Günter Zöchbauer Avatar answered Jan 10 '23 19:01

Günter Zöchbauer


if text comes from TextField use this:

RegExp.escape();

sample:

RegExp rex = RegExp('${RegExp.escape(searchText)}', caseSensitive: false, unicode: true);
like image 38
Ali Bagheri Avatar answered Jan 10 '23 19:01

Ali Bagheri