简体   繁体   中英

DART Conditional find and replace using Regex

I have a string that sometimes contains a certain substring at the end and sometimes does not. When the string is present I want to update its value. When it is absent I want to add it at the end of the existing string.

For example:

int _newCount = 7;
_myString = 'The count is: COUNT=1;'
_myString2 = 'The count is: '
_rRuleString.replaceAllMapped(RegExp('COUNT=(.*?)\;'), (match) {

//if there is a match (like in _myString) update the count to value of _newCount
//if there is no match (like in _myString2) add COUNT=1; to the string

}

I have tried using a return of:

return "${match.group(1).isEmpty ? _myString + ;COUNT=1;' : 'COUNT=$_newCount;'}";

But it is not working.

Note that replaceAllMatched will only perform a replacement if there is a match, else, there will be no replacement (insertion is still a replacement of an empty string with some string).

Your expected matches are always at the end of the string, and you may leverage this in your current code. You need a regex that optionally matches COUNT= and then some text up to the first ; including the char and then checks if the current position is the end of string.

Then, just follow the logic: if Group 1 is matched, set the new count value, else, add the COUNT=1; string:

The regex is

(COUNT=[^;]*;)?$

See the regex demo .

Details

  • (COUNT=[^;]*;)? - an optional group 1: COUNT= , any 0 or more chars other than ; and then a ;
  • $ - end of string.

Dart code:

_myString.replaceFirstMapped(RegExp(r'(COUNT=[^;]*;)?$'), (match) {
     return match.group(0).isEmpty ? "COUNT=1;" : "COUNT=$_newCount;" ; }
)

Note the use of replaceFirstMatched , you need to replace only the first match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM