Tag Info

Hot answers tagged

14

It's easy to search if you break it down: Regex Meaning Mathematica command ------------------------------------------------- \w word character WordCharacter {2,3} repeat 2 to 3 times Repeated[..., {2, 3}] Combine it and use as: StringMatchQ[{"a", "ab", "abc", "abcd"}, Repeated[WordCharacter, {2, 3}]] (* {False, True, True, ...


12

What about this? StringSplit[string, i : NumberString :> i] Ok, everyone's giving answers that actually work with the $, so here's an edit, as @kguler and @MrWizard suggested StringSplit[string, i : ("" | "$" ~~ NumberString) :> i] // StringTrim


10

One possibility: StringMatchQ["Éta", RegularExpression["[[:alpha:]]+"]]


10

A couple of details: Restricting code__ to NumberString will prevent it from being greedy (else it might stop only at the second )) You need to wrap the entire pattern (which is what we want to repeat) in parentheses to respect the precedence of the .. operator. The following pattern works: StringCases[text1, ("ICD-9-CM " ~~ code : NumberString) .. ...


10

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 ...


9

This will download the titles of all articles that transclude the Persondata template, if that's what you're trying to do. Flatten@NestWhileList[ Import["http://en.wikipedia.org/w/api.php?action=query&list=\ embeddedin&eititle=Template:Persondata&format=json&eilimit=500" <> If[Length@# > 1, "&eicontinue=" <> ...


7

Would this do the trick? selectWords[chars_, min_, max_] := Module[{charsset = Union[chars], charstally = Tally[chars], baselist, baselistchars, baselistpicks}, baselist = ToLowerCase[DictionaryLookup[x__ /; min <= StringLength[x] <= max]]]; baselistchars = Select[Characters /@ baselist, Complement[#, charsset] === {} &]; ...


6

Note that Rojo's solution splits the expression containing the dollar sign as well: StringSplit["there are 1234 words and numbers 5678 in here $999", i : NumberString :> i] {"there are ", "1234", " words and numbers ", "5678", " in here $", "999"} If you don't want that splitting to happen, here's one way, using a regex: StringSplit["there are 1234 ...


6

You could simply find the shortest match: StringCases[text1, "(ICD-9-CM " ~~ Shortest[code__] ~~ ")" :> code] {"268.9", "268.9"} If it is possible that there is additional space or other characters a combination may be more robust: text2 = " A Vitamin D Deficiency (ICD-9-CM 268.9) (ICD-9-CM: 268.9) 09/11/2015 01 "; StringCases[text2, ...


6

Total[funca[a,#] & /@ #] & /@ {x,y} There are two Function expressions here which I will refer to as inner and outer. The inner function: funca[a,#] & Is Mapped to the sole argument of the outer function. It will transform a list or other expression like this: funca[a,#] & /@ foo[1, 2, 3] foo[funca[a,1], funca[a,2], funca[a,3]] ...


5

All three of parameters for FileNames can affect the depth at which Mathematica searches for results. It seems like your confusion is a result of interaction among these parameters. This is easily understandable as the documentation for FileNames is not very illustrative. (Indeed my first attempt at answering this question was faulty for the same reason.) ...


5

You're invoking when you should be applying: StringExpression@Riffle[{"a", "b", "c"}, Except[{"=", ","}] ..] (* StringExpression[{"a", Except[{"=", ","}] .., "b", Except[{"=", ","}] .., "c"}] *) VS StringExpression @@ Riffle[{"a", "b", "c"}, Except[{"=", ","}] ..] (* "a" ~~ Except[{"=", ","}] .. ~~ "b" ~~ Except[{"=", ","}] .. ~~ "c" *) Note that ...


5

With RegularExpression you could use: text1 = " A Vitamin D Deficiency (ICD-9-CM 268.9) (ICD-9-CM 268.9) 09/11/2015 01 "; StringCases[text1,RegularExpression@"\\(ICD-9-CM (\\d+(\\.)?(\\d+)?)\\)"-> "$1"]


5

string="The event will be held on 7/10/2013 at 3:30 PM in the room 121 and \ everyone is welcome"; extract the date and time: dateTime=StringCases[string, ___ ~~ x : DatePattern[{"Month", "/", "Day", "/", "Year", " at ", "Hour", ":", "Minute", " ", "AMPM"}] ~~ ___ :> x] (* {"7/10/2013 at 3:30 PM"} *) Make into a date list ...


5

My attempt: First we define the existing row, using dots to represent empty squares, and our hand of 7 letters. row="...t.t...r..e.."; letters="aodalip"; Next define a function to count how many times each of our letters appears in a given string. Also run this function on our letters, to count how many of each we have. ...


5

Since we can not see the source code of Mathematica, we don't know the detailed algorithm Mathematica use to do string pattern searching. But in most other languages, they use KMP algorithm to do explicit string matching. KMP is in fact a very compact design of the DFA pattern matching algorithm. You can find a comparison here. You can see that the ...


4

The following may not fully solve your problem, but seems to logically belong here and is too long for a comment. I do use tabs in my code formatter. This question prompted me to write a palette for the formatter, which was long overdue (it surely can be improved). The palette should work with both "Input"-style and "Program"-style cells. The palette ...


4

expr = -((524288 (29427736469514379027531261659072347 + 58899562724319710108573382000184640 y - 1732944474195510410991057714955859184 z))/(5042560366642267 x - 256 (2446745837411900 + 4901398098088043 y - 144207654645973248 z))^2) with Powers, general approach ClearAll@f; f[expr_] := Replace[ CForm[expr], i_Integer /; And[! ...


4

Here is a rough attempt at implementing what you describe, primarily using StringSplit. Fold[ Flatten @ StringSplit[##] &, StringReplace[text[[1]], "," | "*" :> ""], { StartOfLine ~~ Whitespace ... ~~ DigitCharacter ~~ Except["\n"] .. ~~ "\n", WordBoundary ~~ ("." | ";" | ":") ~~ Whitespace, "\n" } ] // StringTrim {"Since all activities ...


4

You can use the high-level functions to build your string expression for this: StringCases[a1, "struct " ~~ name__ ~~ "{" :> name] (* {{"name1 "}, {"name2"}, {"name3"}, {"name4"}, {"name5"}, {"lastStruct"}} *) If you really need a RegularExpression then there is nothing simpler than starting with the high-level functions and let Mathematica figure out ...


3

Here's an idea (without RegExps): We set up a function fact that extracts the prime factors and wrap them in some head, here we use factors: fact = factors @@ Flatten[ConstantArray @@@ FactorInteger[#]] &; (I use ConstantArray to show all factors) Then we apply this to the expression and replace all integers of absolute value larger than some ...


3

str1 = "Focal Plane: 198' Active Aid to Navigation: Yes *Latitude: \ 35.250 N *Longitude: -75.529 W"; str2 = "Focal Plane: 198.12' Active Aid to Navigation: Yes \ *Longitude: -75.529 W" With string patterns because I do not use regex :) record[string_] := Map[ StringCases[string, # ~~ x : NumberString :> x] /. {} -> "NotAvailable" &, ...


3

Further variations: using StringReplace: List @@ StringTrim /@ StringReplace[string, a : Except[{"$", DigitCharacter}] .. | NumberString | ("$" ~~ NumberString) :> {a}] or, using the same replacement rule in StringCases: StringTrim /@ StringCases[string, a : Except[{"$", DigitCharacter}] .. | NumberString | ("$" ~~ NumberString) :> {a}] ...


3

I prefer the solutions given by Rojo and J.M. to the following one. But if you want to see a working version of your original approach with StringCases and RegularExpression, here is one possibility StringCases[string, RegularExpression["([A-Za-z]|\\s)+|(\\$|\\d)+"]] It returns {"there are ", "1234", " words and numbers ", "5678", " in here ","$999"} ...


2

I originally wrote this to help in guessing a word of known length from a bunch of letters, The word guessing game has 10 letters given so I tried to optimize this for speed. I reworked it here for scrabble: string = "hkxefri"; words = DictionaryLookup[{Apply[Alternatives, Characters[string]]} ..]; joined = StringJoin /@ ...


2

I find great utility in setting up grids using Ctrl, which inserts a place holder at the cursor. The input is interpreted as a List and you can create additional rows using CtrlReturn. Here's a walk-through of your Grid example above: Start with Grid[ and enter the first element in the list. Then press Ctrl,, which produces: Next, enter the second ...


2

MyLogicalExpand[expr_] := With[{patt = "(" ~~ x : (Except[Characters["()"]] ..) ~~ ")" /; ( Implies[#, ! #2] & @@ ( MemberQ[StringPosition[x, LetterCharacter][[;; , 1]], #] & /@ {2, 1})) }, Module[{ cas = StringCases[expr, patt], pos = StringPosition[expr, patt], ...


2

If the link is always at the end you could do something like: StringReplace[tweet, "http://t.co/" ~~ __ ~~ EndOfString :> ""] if not then try tweet2 = "Designing interventions for food security and prevention of malnutrition in Bangladesh #sensemaker http://t.co/wulTxX3vVK and some other stuff" StringReplace[tweet2,Shortest["http://t.co/" ~~ __ ~~ ...


2

Keep in mind Szabolcs comment. But if it is about string manipulation exercise: exp2 = "a$x+b$x$y+a$x[d]+a$x[d$y]"; patt = (NumberString | LetterCharacter) ..; StringReplace[exp2, x : ((patt ~~ "$") .. ~~ patt ) :> StringJoin @@ Riffle[StringSplit[x, "$" -> "["], "]", {4, -1, 3}]] ...


2

As requested, here is one approach using pure RegularExpression. Another difference is the use of Internal`StringToDouble that is faster then ToExpression (velocity test here). getFields[str_String]:=Module[{fields,r}, fields = {"Focal Plane: ", "Latitude: ", "Longitude: "}; ...



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