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


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

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


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


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


3

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


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

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


2

A variation of Kuba's method, using a single StringCases pass with post processing: str2 = "Focal Plane: 198.12' Active Aid to Navigation: Yes *Longitude: -75.529 W" fields = {"Focal Plane: ", "Latitude: ", "Longitude: "}; StringCases[str2, a : fields ~~ x : NumberString :> (a -> ToExpression[x])] fields /. % /. _String :> "NotAvailable" ...


2

This is not a regular expression (or PCRE), but it's a StringExpression that can be used where RegularExpression qualifies: StringCases["Abba", x : LetterCharacter ~~ Shortest[___] ~~ y : LetterCharacter /; ToLowerCase[x] == y] {"Abba"} LetterCharacters are used instead of _ primarily to keep ToLowerCase meaningful.


1

I believe this is what you want. StringCases["Abba", RegularExpression["(.).*(?=(?i:\\1))[a-z]"]] (?=(?i:\\1)) is a lookahead which says, "if the next character matches \1 in any case," but then it also has to match the pattern that occupies the place of the next character, which is [a-z] i.e. only lowercase letters. If it fails to match the outer pair ...


1

If you know that the code you are searching for is a number, then I think the suggestions to use patterns which recognize such number strings are your best bet. For completeness I wanted to show another way which I think is a useful standard approach for such tasks and will work even when you can't make such a premise. The idea is to simply only let code ...


1

I am not sure if this qualifies for an answer but it is too long for a comment therefore I put it here. Feel free to delete. In the examples the string matches the regular expression, meaning the result is not empty. Looking at the output we get StringCases["foo\"bar", RegularExpression[".*\".*"]] // InputForm (* {"foo\"bar"} *) StringCases["foo\"bar", ...



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