WolframLang: RegularExpression vs StringExpression

By Xah Lee. Date: . Last updated: .

RegularExpression vs StringExpression

On syntax, the RegularExpression syntax is more widely understood. StringExpression is more readable. 〔see WolframLang: Regular Expression

They almost have the same power, except:

WolframLang string pattern 2022-04-29 r2g8
WolframLang string pattern 2022-04-29 r2g8
xx = "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green";

(* match string using regex, repace it by captured groups *)
StringCases[xx,
RegularExpression["(\\d+) (red|green|blue)"] :> {"$1","$2"}
]
(* {{8, green}, {6, blue}, {20, red}, {5, blue}, {4, red}, {13, green}} *)

(* same, using wolfram string expression syntax. *)
StringCases[xx,
d:NumberString~~" "~~c:"red"|"green"|"blue" :> {d,c}
]
(* {{8, green}, {6, blue}, {20, red}, {5, blue}, {4, red}, {13, green}} *)

Reference

WolframLang String