Hot answers tagged

16

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


16

First of all, I agree, as OP mentioned in his comment, ANTLR is one of the proper ways to go. Now for this specific task, it might be easier to just compose a parser in the "dirty" way, except we don't have to go so far to regex. In my opinion Mathematica's StringExpression is much more powerful and very suitable for the job. All we have to do is (as OP ...


13

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


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


11

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

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=" <> #[[2,...


9

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


8

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


8

I extended the original question to support piping like the following. wget -qO- "http://google.com" // cat and it outputs the following. cat[][wget[-qO-,http://google.com][]] To get the following. CellPrint@ Cell[BoxData[""], "Input", Evaluatable -> True, CellEvaluationFunction -> Function[ Module[{t}, t = List@ReplaceRepeated[ ...


7

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


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

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


6

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


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. lettercount[str_]:=StringCount[...


5

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


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

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

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 DateList[{...


5

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


5

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


5

This is how to do it without patterns: StringDrop[ txt, StringPosition[txt, "for"][[1, 1]] ;; ] (* Out: "now is the time " *) With patterns you have a few different options, as people have remarked in the comments. They gave you the string pattern version, this is the regular expression version: StringReplace[txt, RegularExpression["for.*$"] -> ""] ...


4

You can get this result by mixing StringExpression with RegularExpression. Regular expressions have the ability to perform a negative look-ahead. This can be used to insure that no numbers which have a decimal followed numbers are matched. getIntegers[s_String] := StringCases[ s, (StartOfString | Whitespace) ~~ u : Repeated["-", {0, 1}] ~~ n : ...


3

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], n}, ...



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