'StringCut' to the left or right of a defined position using Mathematica

两盒软妹~` 提交于 2019-12-05 02:42:08

Here are some alternate solutions:

Splitting by any occurrence of "D":

In[18]:= StringJoin /@ Split[Characters["MTPDKPSQYDKIEAELQDICNDVLELLDSKGDYFRYLSEVASGDN"], #2!="D" &]
Out[18]:= {"MTP", "DKPSQY", "DKIEAELQ", "DICN", "DVLELL", "DSKG", "DYFRYLSEVASG", "DN"}

Splitting by any occurrence of "D" provided it is not preceded by "P":

In[19]:= StringJoin /@ Split[Characters["MTPDKPSQYDKIEAELQDICNDVLELLDSKGDYFRYLSEVASGDN"], #2!="D" || #1=="P" &]
Out[19]:= {"MTPDKPSQY", "DKIEAELQ", "DICN", "DVLELL", "DSKG", "DYFRYLSEVASG", "DN"}
Sasha

I can not build anything much simpler that your code. Here is a regex code, which you might happen to like:

In[281]:= StringSplit@
 StringReplace[str, RegularExpression["(?<!P)D"] -> " D"]

Out[281]= {"MTPDKPSQY", "DKIEAELQ", "DICN", "DVLELL", "DSKG", \
"DYFRYLSEVASG", "DN"}

It uses negative lookbehind pattern, borrowed from this site.


EDIT Adding WReach's cool solution:
In[2]:= StringSplit[str, RegularExpression["(?<!P)(?=D)"]]

Out[2]= {"MTPDKPSQY", "DKIEAELQ", "DICN", "DVLELL", "DSKG", \
"DYFRYLSEVASG", "DN"}

Your first solution isn't that bad, is it? Everything that I can think of is longer or uglier than that. Is the problem there might be spaces in the original string?

StringCases[str, "D" | StartOfString ~~ Longest[Except["D"] ..]]

or

Prepend["D" <> # & /@ Rest[StringSplit[str, "D"]], First[StringSplit[str, "D"]]]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!