我必须使用正则表达式吗?
str = "Now is; the time; for all good; people; to party"
f, sc, l = str.partition(';')
af, *a = str[str.index(';')+1..-1].split(';')
[f+sc+af, *a]
#=> ["Now is; the time", " for all good", " people", " to party"]
步骤:
f, sc, l = str.partition(';')
#=> ["Now is", ";", " the time; for all good; people; to party"]
f #=> "Now is"
sc #=> ";"
l #=> " the time; for all good; people; to party"
idx = str.index(';')+1
#=> 7
b = str[idx..-1]
#=> " the time; for all good; people; to party"
af, *a = b.split(';')
af #=> " the time"
a #=> [" for all good", " people", " to party"]
[f+sc+af, *a]
#=> ["Now is; the time", " for all good", " people", " to party"]
以 OP 为例:
f, sc, l = lines.partition(';')
af, *a = lines[lines.index(';')+1..-1].split(';')
[f+sc+af, *a]
#=> ["</li> <li> Urinary tract infection </li> <li> Respiratory infection\
</li> <li> Sinus problems; and </li> <li> Ear infections",
# " <li> Some more info </li>"]
另一种方式:
b = str.sub(';', 0.chr).split(';')
#=> ["Now is\u0000 the time", " for all good", " people", " to party"]
a[0].sub!(0.chr, ';')
#=> "Now is; the time"
a #=> ["Now is; the time", " for all good", " people", " to party"]