Flutter split a string keeping the delimeter
158
Solution 1
This worked for me.
(?={{)|(?<=}})
Solution 2
You might split using lookarounds with an alternation |
to match both ways before and after the {{...}}
part:
\s*(?={{.*?}})|(?<={{.*?}})\s*
The pattern matches:
-
\s*(?={{.*?}})
Match optional whitespace chars and assert directly to the right a pattern{{...}}}
-
|
Or -
(?<={{.*?}})\s*
Assert a pattern{{...}}}
to the left and match optional whitespace chars
void main() {
var parts = "this is {{A}} sample {{text}} ...".split(RegExp("\\s*(?={{.*?}})|(?<={{.*?}})\\s*"));
print(parts);
}
Output
[this is, {{A}}, sample, {{text}}, ...]
Solution 3
An idea to get the result you are looking for, would be:
- Split the string as you did,
- find all matches,
- insert the matches in your splitted string.
See the following sample that illustrates this idea:
void main()
{
String a = "this is {{A}} sample {{text}} ...";
var allMatches = RegExp("{{(.*?)}}").allMatches(a);
var parts = a.split(RegExp("{{(.*?)}}"));
for(int i = 0; i < allMatches.length; i++) {
int newIndex = 2*i+1;
String? newDelimiter = allMatches.elementAt(i).group(0);
if (newDelimiter!=null) {
parts.insert(newIndex,newDelimiter);
}
}
print(parts); // ["this is ", "{{A}}", " sample ", "{{text}}", " ..."]
}
Author by
Chamupathi Gigara Hettige
Updated on November 23, 2022Comments
-
Chamupathi Gigara Hettige over 1 year
How can I keep the delimiter when split using regex in flutter?
Text:
"this is {{A}} sample {{text}} ..."
What I want is:
["this is", "{{A}}", "sample", "{{text}}", "..."]
I've used the following regex,
"this is {{A}} sample {{text}} ...".split(RegExp("{{(.*?)}}"))
and got,
["this is ", " sample ", " ..."]