This is an example in the help pages (Working with patterns: Highlight Patterns):
SeedRandom[12345];
dna=StringJoin[Table[{"a","c","t"}[[RandomInteger[{1,3}]]],{50}]]
StringReplace[dna,x:("a"~~_~~"a"):>"\!\(\*StyleBox[\""<>x<>"\",
FontColor->RGBColor[1,0,0],FontSize->18,FontWeight->\"Bold\"]\)"]
"\!\(\*StyleBox[\"aca\",\n FontColor->RGBColor[1,FontWeight->\"Bold\"]\)atccttttattactcccacccatcccatc\!\(\*StyleBox[\"ata\",\n FontColor->RGBColor[1,0,0],FontSize->18,FontWeight->\"Bold\"]\)ctatcttctct\!\(\*StyleBox[\"ata\",\n FontColor->RGBColor[1,0,0],FontSize->18,FontWeight->\"Bold\"]\)t"
How to highlight the black part of the DNA with a pattern# (any professional name)?
Method 1: not perfect, some problem see appendix I
rules=MapThread[RuleDelayed,{StringSplit[dna,x:("ag"~~_~~_~~"t"~~_~~"ca")],Style[#,Red]&/@StringSplit[dna,x:("ag"~~_~~_~~"t"~~_~~"ca")]}];
StringReplace[dna,rules]
acttaagctttcgggtgagtgtactgcccactcctagctttcctttagttcttagacgagctggcgcgtagatggctacgtgacttgaatgcattagtgtctagatgcattatggaaccattccaatcgtctcggagggctagtgctgccatcttggttatgtggtatcgtgatttgaatcagtccagcgctataaagtcttcgctgtt~~aggctgca~~ggagccgagggcatcggacgtacaaaatgcgggggtagactgacgaccgcagaggccacatacgacaggccgccggcgtgcgactagatagccgcgagtggggttggctaagcacatcga~~agtgtaca~~gaaaacccctaccccatgagtcgtgcagacgcctccagaaaccagg~~agtttaca~~gcaggacctgagaactaatgttaatgctccatcacctctgcatgcctatccattaagcaaggcacactcagcccctaaaagcgagcggctccccaggagaa
[update1] sub question 1: How to remove the StringExpression (~~) to improve it? thanks for rm and Silva's tips, [this is solved].
**[unsolved-main problem]**sub Question 2: How to achieve the effect in a better way without appendix I's problem? my first thought is to use Except,but failed
Following are the CellPrint effects:
CellPrint@TextCell[Row[List@@StringReplace[dna,rules],""],"Text"]
"acttaagctttcgggtgagtgtactgcccactcctagctttcctttagttcttagacgagctggcgcgtagatggctacgtgacttgaatgcattagtgtctagatgcattatggaaccattccaatcgtctcggagggctagtgctgccatcttggttatgtggtatcgtgatttgaatcagtccagcgctataaagtcttcgctgtt""aggctgca""ggagccgagggcatcggacgtacaaaatgcgggggtagactgacgaccgcagaggccacatacgacaggccgccggcgtgcgactagatagccgcgagtggggttggctaagcacatcga""agtgtaca""gaaaacccctaccccatgagtcgtgcagacgcctccagaaaccagg""agtttaca""gcaggacctgagaactaatgttaatgctccatcacctctgcatgcctatccattaagcaaggcacactcagcccctaaaagcgagcggctccccaggagaa"
Appendix I
When I'm trying golden's suggest to shorten my example, @m_goldberg
SeedRandom[12345]; dna = StringJoin[Table[{"a", "c", "t"}[[RandomInteger[{1, 3}]]], {50}]] rules=MapThread[RuleDelayed,{StringSplit[dna,x:("a"~~_~~"a")],Style[#,Red] &/@StringSplit[dna,x:("a"~~_~~"a")]}]; StringReplace[dna,rules]
Row
to join styled strings, and this is answered in mathematica.stackexchange.com/q/10990/5. Also see WReach's answer on converting toStandardForm
and then usingStringJoin
$\endgroup$Style[#, Red]&
withToString[Style[#, Red], StandardForm]&
in therules
. $\endgroup$