Wolfram: Get SubString, by Pattern

By Xah Lee. Date: . Last updated: .

Get All Matches

StringCases[str, pattern]

Get a list of substrings that match a pattern.

〔see Regular Expression

StringCases

(* extract email address *)
x = "emails john842194@gmail.com and mary441193@yahoo.com etc";
StringCases[ x,
 RegularExpression[ "[a-z0-9]+@[a-z0-9]+\\.com" ],
 IgnoreCase -> True]
(* {john842194@gmail.com, mary441193@yahoo.com} *)
StringCases[str, pattern :> replaceBy]

Get a list of substrings that match a pattern, and replace each by replaceBy

(* get total number of colored balls *)

xx = "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green";

StringCases[xx,
RegularExpression["([0-9]+) (red|green|blue)"] :> ToExpression[ "$1" ]
]

(* {8, 6, 20, 5, 4, 13} *)

Get All Positions

StringPosition

get a list of beginning and end positions.

StringPosition

StringPosition[ "x331 x71 59", RegularExpression["x[0-9]+"] ]
(* {{1, 4}, {6, 8}} *)

Count Occurrence

StringCount

get number of occurrence of a string pattern.

StringCount

StringCount[ "x331 x71 59", RegularExpression["x[0-9]+"] ]
(* 2 *)

WolframLang String