I try to split the list of sentences which have html tags as below:
The <a href="sy.com" id="sy">sky</a> is clear and the <a href="st.com" >stars</a> are twinkling.
They were <a href="etc.com" id="et">excited</a> to see their first sloth.
Douglas figured the best way to <a href="etc.com" id="et">succeed</a> was to do the <a href="opt.com" >opposite</a> of what he'd been doing all his life.
The result I want is as below:
[The, <a href="sy.com" id="sy">sky</a>, is clear and the, <a href="st.com" >stars</a>, are twinkling.]
[They were, <a href="etc.com" id="et">excited</a>, to see their first sloth.]
[Douglas figured the best way to, <a href="etc.com" id="et">succeed</a>, was to do the, <a href="opt.com" >opposite</a>, of what he'd been doing all his life.]
How am I able to do it with RegExp in order to get above result?
CodePudding user response:
For example this is your string:
String str =
"The <a href=\"sy.com\" id=\"sy\">sky</a> is clear and the <a href=\"st.com\" class=\"st\">stars</a> are twinkling. They were <a href=\"etc.com\" id=\"et\">excited</a> to see their first sloth. Douglas figured the best way to <a href=\"etc.com\" id=\"et\">succeed</a> was to do the <a href=\"opt.com\" class=\"op\">opposite</a> of what he'd been doing all his life.";
you clan split it like this:
final reg = RegExp("<[^>]*>");
var result = str.split(reg);
print('result = $result'); // [The , sky, is clear and the , stars, are twinkling. They were , excited, to see their first sloth. Douglas figured the best way to , succeed, was to do the , opposite, of what he'd been doing all his life.]
if you want it with tag, try this(tanks to @JovenDev):
final reg = RegExp("(?=<a)|(?<=/a>)");
var result = str.split(reg);
print('result = $result'); // [The , <a href="sy.com" id="sy">sky</a>, is clear and the , <a href="st.com" >stars</a>, are twinkling. They were , <a href="etc.com" id="et">excited</a>, to see their first sloth. Douglas figured the best way to , <a href="etc.com" id="et">succeed</a>, was to do the , <a href="opt.com" >opposite</a>, of what he'd been doing all his life.]