We’re rewarding the question askers & reputations are being recalculated! Read more.
25

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 (?: … )....


21

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


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


18

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


14

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


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


12

Mathematica allows text searching using regular expressions (based on the PCRE library). It would take some work to re-implement the whole grep functionality within Mathematica, but for your concrete example grep -nr -C 2 <pattern> it is as easy as follows: ClearAll[Grep] Grep[files_List, patt_, c_Integer: 0, style : {__} : {Red, Bold}] := ...


11

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


11

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


11

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


11

Fix the group name. Beats me why the change - first works in 9.X Win., but not on 10.3 Win... StringPosition["{tes,{1,2,3},t}", RegularExpression["(?P<0>{([^{}]|(?P>0))*})"]] RegularExpression::msg84: Group name must start with a non-digit in RegularExpression[(?P<0>{([^{}]|(?P>0))*})]. >> StringPosition["{tes,{1,2,3},t}", RegularExpression["...


11

I'd do the minimum necessary to make a legitimate, unambiguous Mathematica expression, and then let Mathematica rewrite it. stepexpr[s_] := ToExpression[StringReplace[s, {"(" -> " dummy[", ")" -> "]"}]] /. op_Symbol dummy[args__] -> op[args] /. dummy -> List This replaces () expressions with a dummy[] function in the string, making a legal ...


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

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


9

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


8

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


8

The conclusion of Mr. Wizard's and MarcoB's comments is that there is no function to convert regular expressions into string patterns, but there is a function to convert string patterns into regular expressions called StringPattern`PatternConvert: StringPattern`PatternConvert[StartOfString ~~ "a" ~~ __ ~~ "b" ~~ EndOfString] {"(?ms)\\Aa.+b\\z", {}, {}, ...


8

I think we are out of luck. I cannot offer a definitive answer to this question, but I will share some observations. It is only with the release of PCRE2 in 2015 that substitution replacement string syntax became standardized through the function pcre2_substitute. The original PCRE library did not offer substitution functionality so it was left up to ...


8

Use named Pattern to extract a part of matched substring: StringCases[#, str : Shortest[StartOfString ~~ ___] ~~ "!" :> str] & /@ s {{{"This is small string 2 "}}, {{"There is string 5 "}}, {{"This is String n "}}} or StringCases[#, str : Shortest[StartOfString ~~ ___] ~~ "!" :> str] &@Flatten@ s {{"This is small string 2 "}, {"There is ...


8

Is this what you want? StringReplace[ text , pre:("SYMATTR InstName U" ~~ d : DigitCharacter..) :> StringTemplate[ "`1`\nSYMATTR Value `2`" ][pre, StringJoin[StringTemplate["E`1`=`2``1` "][#, d] & /@ Range[8]]] ] "SYMATTR InstName U1 SYMATTR Value E1=11 E2=12 E3=13 E4=14 E5=15 E6=16 E7=17 E8=18 " Sorry I'm not very good with ...


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


7

This is a good place to use the curried "operator form" of one of the string match predicates, such as: Cases[list, {_, _?(StringMatchQ["ab*"])}] (* {{"1", "abc"}, {"2", "abd"}} *)


7

Update As recommended in the comments by @b3m2a1, you can also use RunProcess as a simpler way to execute grep. You need to supply the command as a list of the command plus the space delimited arguments and set the ProcessDirectory. To do a recursive search for NotebookDirectory in notebook files enter the following: cmd = "grep -RH \"NotebookDirectory\" ...


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, Shortest["(...


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


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