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 - 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 - 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 - Adding a thick curve to a regionplot

Suppose we have the following simple RegionPlot: f[x_] := 1 - x^2 g[x_] := 1 - 0.5 x^2 RegionPlot[{y < f[x], f[x] < y < g[x], y > g[x]}, {x, 0, 2}, {y, 0, 2}] Now I'm trying to change the curve defined by $y=g[x]$ into a thick black curve, while leaving all other boundaries in the plot unchanged. I've tried adding the region $y=g[x]$ and playing with the plotstyle, which didn't work, and I've tried BoundaryStyle, which changed all the boundaries in the plot. Now I'm kinda out of ideas... Any help would be appreciated! Answer With f[x_] := 1 - x^2 g[x_] := 1 - 0.5 x^2 You can use Epilog to add the thick line: RegionPlot[{y < f[x], f[x] < y < g[x], y > g[x]}, {x, 0, 2}, {y, 0, 2}, PlotPoints -> 50, Epilog -> (Plot[g[x], {x, 0, 2}, PlotStyle -> {Black, Thick}][[1]]), PlotStyle -> {Directive[Yellow, Opacity[0.4]], Directive[Pink, Opacity[0.4]],