Use Regex

From Cuis CookBook
Jump to navigation Jump to search

Regex is large subject. For the moment I am going to put here just a list of examples.

  • First things first, to work with Regexp you need to load the appropriate package
Feature require: 'Regex'.
  • Important, matchesRegex tries to match a full string, if you want to scan for a substring use search: .
  • Does the string match a regex?
'hello123' matchesRegex: 'he'. " => false " 
'hello123' matchesRegex: 'he.*'. " => true "
  • Find all occurrences of a regex
' 2019-08-01T00:00:00+00:00' allRegexMatches: '\d+'. 
" => an OrderedCollection('2019' '08' '01' '00' '00' '00' '00' '00') "
  • Split a string, classic applications: CSV parsing, get a list of words from a sentence.
',' asRegex split: '123,c1,12.4 , Foo bar, baz'. 
" => an OrderedCollection('123' 'c1' '12.4 ' ' Foo bar' ' baz') "
  • Substitute each regex match with a given string
'ab cd ab' copyWithRegex: '(a|b)+' matchesReplacedWith: 'foo' . 
" => 'foo cd foo' "
  • Substitute each regex match with the result of Block value
'ab cd ab' copyWithRegex: '(a|b)+' matchesTranslatedUsing: [:each | each asUppercase] . 
" => 'AB cd AB' "
  • Grouping in regex
str := 'Today is 05-Aug, it is about 09:34, and we are near Verona. ' . 
rex := '(\d+)\:(\d+)' asRegex . 
rex class. " => RxMatcher " 
rex search: str. " => true # true, a match has been found. " 
rex subexpressionCount. " => 3 # number of elements matched. " 
rex subexpression: 1. " => '09:34' # first element is always the whole match. " 
rex subexpression: 2. " => '09' # then there are groups... " 
rex subexpression: 3. " => '34' "
  • Observe well that the matching substrings are stored into the Regex object.

Dr. Nicola Mingotti updated this on 06-Sep-2021. Examples were run in a Cuis a bit older than Cuis5.0-4834.image.