NTMS
NTMS

Reputation: 846

How to match sequences of consecutive Money like characters string in Dart?

I have sequences of consecutive money like characters string like:

"000000000012735"

and I want use regex to cover sequences of consecutive Money like characters string to Money type or in Dart double like:

"127.35"

Incoming sequences of consecutive Money like characters string length is 15.

I am just trying to learn regex and I try to use:

final value =  "000000000012735".replaceAllMapped(RegExp(r'.{13}'), (match) => "${match.group(0)} ");
 print('value: $value');

but it dived string and doesn't add . in empty space as:

value: 0000000000127 35

What is correct regex pattern to convert above format as I describe above in Dart?

Upvotes: 0

Views: 164

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You can use

final text = '000000000012735';
print(text.replaceFirstMapped(RegExp(r'^0*(\d+)(\d{2})$'), (Match m) => 
   "${m[1]}.${m[2]}"));

The output is 127.35.

The regex matches

  • ^ - start of string
  • 0* - zero or more 0 chars
  • (\d+) - Group 1: one or more digits
  • (\d{2}) - Group 2: two digits
  • $ - end of string.

Note that since one replacement is expected, there is no need using replaceAllMapped, replaceFirstMapped will do.

Upvotes: 2

Related Questions