Skip to main content

performance tuning - Extract substring up to specific character non-inclusive


I was wondering if there is a way with StringCases to start at the beginning of a string and stop one character before a known character.



s = {{"This is small string 2 !"}, {"There is string 5 ! Or is it 2?"},
{"This is String n !"}};

My problem is that I have a lot of these strings and not all are the same length and some have more characters after the exclamation mark.


I know it involves this code:


StringCases[#, Shortest[StartOfString~~___~~ ????????]]& /@ s

But I don't know how to finish it (where the ??????? are).


I would like my end result to look like this:


final={{"This is small string 2 "},{"There is string 5 "},{"This is String n "}}


I have tried searching for this on the forums and have had no luck.


If you could provide an answer or even a direction to go, that would be very much appreciated!


Thanks!


Also, if this isn't the most efficient way of doing this, or if you have any questions, please let me know.



Answer



Use named Pattern to extract a part of matched substring:


StringCases[#, str : Shortest[StartOfString ~~ ___] ~~ "!" :> str] & /@ s



{{{"This is small string 2 "}}, {{"There is string 5 "}}, {{"This is String n "}}}

or


StringCases[#, str : Shortest[StartOfString ~~ ___] ~~ "!" :> str] &@Flatten@ s


{{"This is small string 2 "}, {"There is string 5 "}, {"This is String n "}}



As Martin notes in the comments, another approach is to capture Longest sequence of characters from a negated character class. In this case we don't have to use a named pattern which introduce additional overhead, hence this approach should be more efficient. Since string patterns by default are greedy, Longest can be omitted in this case:



StringCases[#, StartOfString ~~ Except["!"] ...] &

Translating StringExpressions into equivalent regular expressions sometimes gives substantial increase in performance: this is what Mathematica always does under the hood, but not always in the optimal way. Here is verbatim semantic translation:


StringCases[#, RegularExpression["^[^!]*"]] &

(read here on how to find out what a regex Mathematica generates from a StringExpression).


And another regex without capturing group and without use of a negated character class:


StringCases[#, RegularExpression["^.*?(?=!)"]] &

Note that this last regex can't be expressed as a combination of usual Wolfram Language patterns because it uses a positive lookahead zero-length assertion which has no equivalent in the world of Wolfram Language symbolic pattern objects.





Performance comparison


Here is a timing comparison of the all suggested solutions (on a very large number of short strings):


$HistoryLength = 0;
s1 = ConstantArray["There is string 5 ! Or is it 2?", 2*10^5];

{First@AbsoluteTiming[# /@ s1], #} & /@ {
StringCases[#, str : Shortest[StartOfString ~~ ___] ~~ "!" :> str] &,
StringCases[#, RegularExpression["^(.*?)!"] -> "$1"] &,
StringCases[#, StartOfString ~~ Except["!"] ...] &,

StringCases[#, RegularExpression["^[^!]*"]] &,
StringCases[#, RegularExpression["^.*?(?=!)"]] &,
StringDelete[#, "!" ~~ ___] &, StringExtract[#, "!" -> 1] &,
StringTake[#, StringPosition[#, "!", 1][[1, 1]] - 1] &,
StringDrop[#, {StringPosition[#, "!", 1][[1, 1]], -1}] &} //
Grid[#, Frame -> All, Alignment -> Left, FrameStyle -> Directive[Thin, LightGray]] &

MaxMemoryUsed[]



grid


102886352

Another comparison suggested by Martin (on a string where it takes a while to find the "!"):


$HistoryLength = 0;
s2 = StringRepeat["There is string 5 ", 10^5] <> "! Or is it 2?";
results = {};

{(AppendTo[results, #2]; #1) & @@ AbsoluteTiming[#@s2], #} & /@ {
StringCases[#, str : Shortest[StartOfString ~~ ___] ~~ "!" :> str][[1]] &,

StringCases[#, RegularExpression["^(.*?)!"] -> "$1"][[1]] &,
StringCases[#, StartOfString ~~ Except["!"] ...][[1]] &,
StringCases[#, RegularExpression["^[^!]*"]][[1]] &,
StringCases[#, RegularExpression["^.*?(?=!)"]][[1]] &,
StringDelete[#, "!" ~~ ___] &,
StringExtract[#, "!" -> 1] &,
StringTake[#, StringPosition[#, "!", 1][[1, 1]] - 1] &,
StringDrop[#, {StringPosition[#, "!", 1][[1, 1]], -1}] &} //
Grid[#, Frame -> All, Alignment -> Left, FrameStyle -> Directive[Thin, LightGray]] &


SameQ @@ results

MaxMemoryUsed[]


grid


True

82707472


The conclusion: Martin's solution via negated character class with greedy quantifier outperforms others in general: RegularExpression["^[^!]*"]. See this dedicated Q&A about why the equivalent string expression StartOfString ~~ Except["!"] ... is two orders of magnitude slower.


Comments

Popular posts from this blog

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1....