januw a
januw a

Reputation: 2248

Dart regular expression using `$1`

I want to use $1 in adart regular expression to get the grouping in the expression.

Just like javascript regular expressions.

void main() {
  // javascript
  // 'hello-world'.replace(/-(w)/, '+$1'); // hello+world

  print('hello-world'.replaceAll(RegExp(r'-(w)'), '+\$1')); // hello+$1orld
}

Completely unexpected.

Expected result hello+world, actual resulthello+$1orld

Upvotes: 0

Views: 579

Answers (1)

lrn
lrn

Reputation: 71623

The Dart replaceAll method does not treat its second argument as a replacement pattern.

Rather than introduce a new language for specifying replacements in a string, Dart allows you to use a normal Dart expression to compute the replacement. Dart has a short syntax for functions, so this is not much longer than the string, but it allows you to insert arbitrarily complicated computations when necessary.

So, use the replaceAllMapped function and write the replacement as follows:

print('hello-world'.replaceAllMapped(RegExp(r'-(w)'), (m) => '+${m[1]}'));

For this particular example, the RegExp is so simple that you can replace with a plain string:

print('hello-world'.replaceAll(RegExp(r'-(?=w)'), '+'));

This replaces a - with a + only when the - is followed by a w.

Upvotes: 2

Related Questions