Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can you include the delimiter in a .split string in dart?

I have a String as follows:

var _quotedText = "Text1[John;1234]Text2";

Which I want to split into a list as follows:

final List<String> _splitQuotedText = _quotedText.split(RegExp(r"\[([A-z].+);([0-9]+)\]"));

My list comes out as:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['Text1', 'Text2']

But I’d like it to actually comes out as:

['Text1', '[John;1234]Text2']

Meaning the delimiter should be included with the match, and ideally the delimiter would be considered the "start" for a given item.

Is there any kind of straightforward way to tackle this?

>Solution :

A simple way to do this is to use regex’s lookahead function.

A lookahead will match whatever is before your lookahead, we can use it to match the space before your delimiter and use that as a delimiter:

A lookahead looks like this:

(?= ... )

So your new regex looks like this:

(?=\[([A-z].+);([0-9]+)\])

Here is your example:

void main() {
  var myString = "Text1[John;1234]Text2";
  List<String> myList = myString.split(RegExp(r"(?=\[([A-z].+);([0-9]+)\])"));

  print(myList); // ['Text1', '[John;1234]Text2']
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading