Home > Software engineering >  Strip any hashtags at the end of a string in Dart
Strip any hashtags at the end of a string in Dart

Time:10-21

I'm currently extracting hashtags from a string and adding them to an array but how can I remove them from the string as well provided they are located by the end?

For example:

// Random string with tags
String message = "Hello #tag1 and #tag2 the end #tag3 #tag4";
RegExp regex = RegExp(r"\B#\w\w ");
List<String> tags = [];

// Add each tag to list
regex.allMatches(message).forEach((match){
  tags.add(match.group(0)!);
});

How to remove #tag3 #tag4 from the original string so it's updated to look:

Hello #tag1 and #tag2 the end

The only reason I'm keeping #tag1 and #tag2 is because it would look weird if they were taken out since it's within a sentence. Note that the string can be anything.

Original code taken from here.

CodePudding user response:

Try this:

String text = "Test #tag1 and #tag2 end #tag3 #tag4";
String resultText = "";
var l = text.split(" ");
int index = l.lastIndexWhere((element) => !element.contains('#'));
l.removeRange(index   1, l.length);
resultText = l.join(' ');
print("resultText= $resultText"); //resultText= Test #tag1 and #tag2 end
  • Related