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

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


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


8

TL;DR Recursive expressions are possible using native string patterns in Mathematica, but can be difficult to write correctly, and might perform very poorly. Difficult To Write? As @Leonid's solution shows, it is possible to express recursive patterns without resorting to regular expressions. However, recursive string patterns can be more difficult to ...


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] === {} &]; ...


7

This response is really just an extended comment in support of the hypothesis that Mathematica is anchoring the pattern to the beginning and end of the string. In addition to the compelling behavioural observations reported in @2012rcampion's response, I submit the evidence of the following expressions: ClearSystemCache[] Trace[StringMatchQ["a", a_], ...


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


6

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


6

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


6

NOTE Apparently, the solution below isn't quite right, as demonstrated by WReach in his answer. It is, therefore, better to treat this one as a simple illustration of the idea, while the correct one is given by the answer of WReach. In your approach, you need delayed evaluation of the inner pattern bb, to avoid infinite recursion. Here is one way: bb = ...


6

For me (that is very personal indeed), StringExpressions in Mathematica are much more transparant than regular expressions. Here are two StringExpressions for your strings: p1 = NumberString ~~ ".2" ~~ DigitCharacter ~~ DigitCharacter ~~ "nc"; p2 = NumberString ~~"." ~~ (x : NumberString /; 200 <= ToExpression[x] < 300) ~~ "nc"; teststrings = ...


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

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

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

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

Using Regexes: StringReplace["aaabccccc", RegularExpression["(\\w)(\\1+)"] :> StringJoin["$1", Array["x" &, StringLength@"$2"]]] (* "axxbcxxxx" *)


5

One way to do this using Mathematica's native string patterns is like this: StringReplace["aaabccccc", xs:((x:WordCharacter)..) :> StringPadRight[x, StringLength@xs, "x"] ] (* "axxbcxxxx" *) Here is the same replacement expressed using a RegularExpression: StringReplace["aaabccccc", RegularExpression["((\\w)\\2+)"] :> StringPadRight["$2", ...


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

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


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


3

I realized I should probably double-check that the regular expression was correct... it worked on regex101, but I wanted to test it on my computer, just in case. Running the command: grep -P '(.)((?R)|.?)\1' /usr/share/dict/words resulted in matching every word that contained a palindrome inside it (e.g. Abbott -> bb). Of course, simply adding ^$ to ...


3

You can use StringMatchQ and HexadecimalCharacter to check the list for non-hex items. First I'll make some hexadecimal strings and insert some non-hex ones. hexStrings = IntegerString[RandomInteger[{10, 30000}, 100], 16]; AppendTo[hexStrings, "zxc2"]; PrependTo[hexStrings, "x34c"]; Now we can Map the StringMatchQ function over the list using a Repeated ...



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