86

In this response, I will focus upon the programming paradigm change when moving from Java to Mathematica. I will emphasize two differences between the languages. The first concerns the "feel" of writing Mathematica code. The second is about how iteration is expressed. The "Feel" of Mathematica Java is a reasonably conventional programming language, ...


48

Preamble and motivation While I am much late to the party here, I hope this answer will not be totally useless. This is a first in a series of posts where I will advocate a wider use of Java in our workflow, and present/describe certain toolset to reduce the mental overhead of this. So, my motivation here is not to provide a faster or more elegant solution, ...


42

The undocumented System`Dump`showStringDiff function neatly does the diff and highlights it for you. The simplest usage is: System`Dump`showStringDiff[text1, text2] You can choose custom colours for the highlights with the Styles option. You can also change the background, font weight, add a strikethrough, etc.: System`Dump`showStringDiff[text1, text2, ...


41

Use Row to join them: Omega = "text"; joined = Row[{Style[Omega, Lighter[Blue, .1]], Style[Omega, Darker[LightBlue, .1]]}]; Print[joined]


38

Given two styled items: omega = "text" items = { Style[omega,Lighter[Blue,.1]], Style[omega,Darker[LightBlue,.1]] } We can produce a single string with both stylings if we convert each item into a StandardForm string prior to joining them: Apply[StringJoin, ToString[#, StandardForm] & /@ items] The following screenshot shows the results:


31

Using StringPattern`PatternConvert we can find the regexp into which Mathematica converts the original string expression: StringPattern`PatternConvert[Except["b"] .. ~~ "b"][[1]] "(?ms)(?:[^b])+b" The only difference as compared to the direct semantic translation is that the negated character class [^b] is enclosed by redundant non-capturing group (?: … )....


30

There are three different mechanisms provided for matching string patterns in Mathematica. Each of these must be used within functions that are equipped to handle strings. You cannot, for instance, use: {"abc", "def", "ghi"} /. "a*" -> 1 Replace["downwind", "downw" -> "resc"] to any effect. Instead you would use: {"abc", "def", "ghi"} /. x_String ...


30

StringReplace method After reading other answers I was inspired to write a new method. I place it first because it is almost as concise as the method below yet it is more robust (and safe) because it preserves strings as strings. str = "[can {and it(it (mix) up)} look silly]"; StringReplace[str, {"["|"{"|"(" -> -1, "]"|"}"|")" -> 1, " " -> 0}] //...


28

Mathematica supports two related functions, LongestCommonSequence[] and LongestCommonSubsequence[]. The first one finds the longest (contiguous or non-contiguous) sequence common to the two strings given as arguments to it: LongestCommonSequence["AAABBBBCCCCC", "CCCBBBAAABABA"] "AAABB" while the second function is constrained to give the longest contiguous ...


26

From the documentation, though IMHO not easy to find: StringReplace["this is a test", WordBoundary ~~ x_ :> ToUpperCase[x]] "This Is A Test" István Zachar highlighted a problem with WordBoundary that I'm still trying to understand. Nevertheless it seems that one can use: strAcc = "árv ízt űr őt ük örf úr óg ép"; StringReplace[strAcc, z : (...


25

My guess is that WRI made an explicit design decision to separate general patterns and string patterns in order to manage ambiguities where the two syntaxes overlap. As a simple example, consider the pattern (_~~"x")... When we draw no distinction between general patterns and string patterns, then this expression is ambiguous. If interpreted as a general ...


24

For most strings you can use simply: ToString[string] Or more rigorously: ToString[string, OutputForm] Observe: If your styled string includes two dimensional formatting that you do not wish to change you will find OutputForm unacceptable. Of course the 2D formatting itself will mean that the string cannot be in a "plain" form, but we can still strip ...


23

Ok, since you dismissed SplitBy, which IMO is quite clean, and you wanted other's ideas, here's an unconventional solution that relies on a side-effect of how StringJoin works :) list = {"a", "b", 1, 2, 3, 4, "a", 2, 2, 2, "edg", "?"}; List @@ Quiet@StringJoin@list (* {"ab", 1, 2, 3, 4, "a", 2, 2, 2, "edg?"} *) I wouldn't recommend this for production code....


23

This is a bug in version 10.1.0. We decided it was serious enough to warrant a fix via an automatic paclet update. The paclet has been pushed live and Mathematica should install it automatically once it does a periodic check with the paclet server. It should take about a week or so. To install it right away, you can do PacletInstall["StringPatternFix"]. You ...


23

Here we go... highlightString[board_, str_] := With[{l = Characters[str]}, board // horizontal[l] // vertical[l] // diagonal[l] // diagonalReversed[l]] horizontal[letters_][board_] := applyStyle[letters] /@ board vertical[letters_][board_] := Transpose[applyStyle[letters] /@ Transpose[board]] diagonal[letters_][board_] := diagonalD[applyStyle[letters] /@ ...


22

A very simple and straightforward test for square-freeness (and should be reasonably fast) is: squareFreeQ[str_] := StringFreeQ[str, x__ ~~ x__] Testing on your inputs: squareFreeQ["0101"] (* False*) squareFreeQ["0102012021"] (* True *) You can then possibly restrict this further to operate only on certain alphabets using Repeated and Alternatives. ...


22

Here's a start (perhaps it's better to say continuation since you've already gotten started): Row@Flatten[sa /. {a_, b_} :> { Style[a, Red], "(", Style[b, Green], ")"}] By capturing the word fragmentth to the left and right of a, you thhould be able to end up with thomething more like:


22

str = {"1,2,3,5,10,12,13,17,26,30,32,41,42,43,113,115,121,125"} Flatten@ToExpression@StringSplit[str, ","] Short explanation: After executing StringSplit you get a list of separated "StringNumbers" like {{"1", "2", ... "125"}} ToExpression converts these "StringNumbers" to Integers. Flatten removes the outermost brackets. You can even omit Flatten by ...


21

Preamble What happens can be understood when we recall that Rule is a scoping construct. The general issues related to variable renamings in scoping constructs have been considered in more details in this answer. General Now, to this particular case. When the code runs, the external RuleDelayed considers the situation "dangerous" and performs variable ...


20

Also, using pattern matching,just in case: {{a, b, c, d, e, f, g}, {x, a, r, b, c, j}} /. {{___, Longest[y__], ___}, {___, y__, ___}} -> {y} (* -> {b, c} *) Edit With this approach you can do one thing that seems not trivial by using the faster LongestCommonSequence[] function: finding the maximal common subsequence among several lists: {{1, 2, 3, ...


20

To remove accents from a string I use this function: removeAccent[string_] := Module[{accentMap,l1,l2}, l1 = Characters["ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"]; l2 = Characters["SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"]; accentMap = Thread[l1 -> l2]; StringReplace[string, accentMap] ] So, if ...


20

It might be overkill, but with: DictionaryLookup[{"German", All}] you get a list of every German word. To be a bit more precise, you could then narrow things with string searches, i.e. DictionaryLookup[{"German", "a" ~~ ___ ~~ "b"}] gets you a list of words that begin with a and end with b. Full documentation is here.


20

str = "[can {and it(it (mix) up)} look silly]"; i = 10; StringJoin @@ Last[Replace[Characters@str, {"[" | "(" | "{" :> Sow[" ", --i], "]" | ")" | "}" :> Sow["", ++i], c_ :> Sow[c, i]} , 1] ~Reap~ Range@10] (* " mix it up and it can look silly" *) This just scans through the characters one at a time and Sows them with an integer tag. The ...


20

A combination of StringJoin and Riffle: res = StringSplit["a b c d e f g"," "]; StringJoin@Riffle[res," "]


19

Short Version: Use ".*\".*" to match an embedded quote, ".*\\\\.*" to match an embedded backslash. This question deals with two distinct syntaxes -- Mathematica string syntax and regular expression syntax. Both syntaxes use \ as an escape character, so we'll need separate the two levels to see what is happening. First, let's deal with the Mathematica ...


19

Here's my suggestion: mylist = {"[a]", "a", "a", "[b]", "b", "b", "[ c ]", "c", "c"}; Split[mylist, ! StringMatchQ[#2, "[*"] &] and we get: {{"[a]", "a", "a"}, {"[b]", "b", "b"}, {"[ c ]", "c", "c"}}


19

StringCases["thiru3", x : NumberString :> ToExpression[x]] (* {3} *) First[%] (* 3 *) {NumberQ[%], Head[%]} (* {True, Integer} *)


19

Actually, WordBoundary won't always work correctly (see this thread): str = "the lazy dog jumped over the quick brown fox."; strAcc = "árv ízt űr őt ük örf úr óg ép"; StringReplace[str, WordBoundary ~~ x_ :> ToUpperCase[x]] StringReplace[strAcc, WordBoundary ~~ x_ :> ToUpperCase[x]] "The Lazy Dog Jumped Over The Quick Brown Fox." "Árv Ízt űR őT Ük ...


19

Does this do the job? links = Import[ "http://www1.ncdc.noaa.gov/pub/data/cmb/drought/weekly-palmers/2005/", "Hyperlinks"] {"http://www1.ncdc.noaa.gov/pub/data/cmb/drought/weekly-palmers/2005/?C=N;O=D", "http://www1.ncdc.noaa.gov/pub/data/cmb/drought/weekly-palmers/2005/?C=M;O=A", "http://www1.ncdc.noaa.gov/pub/data/cmb/drought/weekly-palmers/...


19

There are a number of subtle details at work here. Perhaps the prominent one is that in string expressions, unlike expression patterns, Longest and Shortest do not actually refer to the maximal or miminal possible match in a string. Rather, they correspond to the regular expression concepts of greedy and ungreedy. Furthest Apart Identical Characters? The ...


Only top voted, non community-wiki answers of a minimum length are eligible