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:
['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']
}