WolframLang: String Match

By Xah Lee. Date: . Last updated: .

Check a Pattern Exist

These functions take a string pattern. either Regular Expression or String Expression.

StringStartsQ

StringStartsQ

StringEndsQ

StringEndsQ

StringMatchQ

StringMatchQ

StringMatchQ["abc", RegularExpression[ "..." ] ] === True

(* must match the whole string *)
StringMatchQ["abc", RegularExpression[ "." ] ] === False
StringContainsQ

StringContainsQ

StringContainsQ[ "some thing", "th", IgnoreCase -> True ]
StringFreeQ

StringFreeQ

Get Substring by Pattern

StringCases[str, pattern]

Get a list of substrings that match a pattern.

[see Regular Expression]

StringCases

(* extract email address *)

x = "emails john@gmail.com and mary441@yahoo.com etc";

StringCases[
 x,
 RegularExpression[ "[a-z0-9]+@[a-z0-9]+\\.com" ],
 IgnoreCase -> True]

(* {john@gmail.com, mary441@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} *)
StringPosition

get a list of beginning and end positions.

StringPosition

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

get number of occurrence of a string pattern.

StringCount

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

WolframLang String