View Category
Check if a string matches a regular expression
Display
"ok" if "Hello" matches /[A-Z][a-z]+/
haskell
import Text.Regex.Posix
main = if "Hello" =~ "[A-Z][a-z]+" then putStrLn "OK" else return ()
main = if "Hello" =~ "[A-Z][a-z]+" then putStrLn "OK" else return ()
Check if a string matches with groups
Display
"two" if "one two three" matches /one (.*) three/
haskell
import Text.Regex
main = case matchRegex (mkRegex "one (.*) three") "one two three" of
Nothing -> return ()
Just (x:_) -> putStrLn x
main = case matchRegex (mkRegex "one (.*) three") "one two three" of
Nothing -> return ()
Just (x:_) -> putStrLn x
Check if a string contains a match to a regular expression
Display
"ok" if "abc 123 @#$" matches /\d+/
haskell
import Text.Regex
main = case matchRegex (mkRegex "\d+") "abc 123 @#$" of
Nothing -> putStrLn "not ok"
Just _ -> putStrLn "ok"
main = case matchRegex (mkRegex "\d+") "abc 123 @#$" of
Nothing -> putStrLn "not ok"
Just _ -> putStrLn "ok"
Loop through a string matching a regex and performing an action for each match
Create a list
[fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
haskell
import Text.Regex
getParenNum s = case matchRegexAll re s of
Nothing -> []
Just (_,_,after,[word,num]) -> (word ++ num):getParenNum after where
re = mkRegex "\\((\\w+)\\):([[:digit:]]+)"
main = putStrLn (show (getParenNum "(fish):1 sausage (cow):3 tree (boat):4"))
getParenNum s = case matchRegexAll re s of
Nothing -> []
Just (_,_,after,[word,num]) -> (word ++ num):getParenNum after where
re = mkRegex "\\((\\w+)\\):([[:digit:]]+)"
main = putStrLn (show (getParenNum "(fish):1 sausage (cow):3 tree (boat):4"))
Replace the first regex match in a string with a static string
Transform
"Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
Replace all regex matches in a string with a static string
Transform
"She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
Replace all regex matches in a string with a dynamic string
Transform
"The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
