StefanSpeterDev
StefanSpeterDev

Reputation: 157

Get part of a string using a RegEx in Dart

I have this sentence commerce_product--default which I want to extract only the last part so here default, to do so I'm using this RegEx RegExp(r'-\s*\K[^-]+$')

Now I try to display it in my code but I didn't find the method to do it, I've tried with stringMatch or replaceAll like this :

final type = 'commerce_product--default';
final newType = type.replaceAll(RegExp(r'-\s*\K[^-]+$'), type);

but it didn't work.
Thanks for the help

Upvotes: 0

Views: 2658

Answers (3)

lrn
lrn

Reputation: 71623

To match everything after the last -, you should just match all trailing non-- characters:

var lastPartRE = RegExp(r"[^-]*$");
var lastPart = lastPartRE.firstMatch()?.group(0);

This matches all trailing non-- characters.

If the string does not contain any -, then it just matches the entire string. If you want a non-match in that case, you can put in a requirement for the ?:

var afterLatDashRE = RegExp(r"(?<=-)[^-]+$");

This would require a minus character before the match.

I'd probably just omit the RegExp entirely and do it with code:

String lastPart(String text) {
  return text.substring(text.lastIndexOf("-") + 1);
}

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163267

To replace all before the last occurrence of - you could also match the whole line until the last occurrence of it and assert that what follows is 1+ times any char except - until the end of the string.

In the replacement use an empty string.

^.*-\s*(?=[^-]+$)

Regex demo | Dart demo

final type = 'commerce_product--default';
final newType = type.replaceAll(RegExp(r'^.*-\s*(?=[^-]+$)'), '');
print(newType);

Output

default

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You are using a PCRE pattern that is not supported in Dart regex. You may use

final type = 'commerce_product--default';
final newType = RegExp(r'-\s*([^-]+)$').firstMatch(type);
if (newType!=null) {
  print(newType.group(1));
}

It is basically the same (see the regex demo), but without \K match reset operator, and the part you need to extract is wrapped with capturing parentheses. These parentheses create a group (here, with ID = 1) that you may access (with newType.group(1)) after a match is found (if (newType!=null) check is thus important).

I suggest using .firstMatch() here since you expect a single match at the end of the string.

Upvotes: 1

Related Questions