3

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.

6
  • Since string #2 has no match, no replacement can be done. Do you want to match COUNT=<digits> after count is:? Is count is: string always present? Commented Jul 29, 2020 at 8:25
  • count is: is not a reliable match as it may change. If no match is found for 'COUNT=<digits>; I want to add it to the string. Commented Jul 29, 2020 at 8:30
  • Where? At the end? Commented Jul 29, 2020 at 8:32
  • Yes- I want to append it to the end of the string. Commented Jul 29, 2020 at 8:40
  • One more: do you expect COUNT=<digits>; always at the end of string? Commented Jul 29, 2020 at 8:41

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.