7. Patterns
The report needed only fixed separators. When the text has a shape rather than a separator, as an address, a date or a setting, describe the shape with a regular expression.
Search
call re%compile('(?P<user>\w+)@(?P<host>[\w.]+)')
m = re%search('write to ann@example.org or bob@test.net')
print '(L1,1X,A,1X,2I3)', m%found, m%group(0)//'', m%span(0)
print '(A,1X,A)', m%group('user')//'', m%group('host')//''compile turns the pattern into a regex once; search finds the leftmost match. (?P<user>\w+) is a group named user: one or more word characters. group returns the text of a group by number or name, span its first and last byte.
All the matches
all = re%finditer('write to ann@example.org or bob@test.net')
do i = 1, size(all)
print '(I0,2A)', i, ': ', all(i)%group('user')//''
enddofinditer returns every match, left to right; findall would return only their texts.
Replace and split
line = re%sub('\g<user> at \g<host>', 'write to ann@example.org or bob@test.net')
print '(A)', line%chars()
parts = re_split('a, b ;c', '\s*[,;]\s*')
print '(3(A,"|"))', (parts(i)%chars(), i=1, size(parts))In the template of sub, \g<user> is the text of the group user. re_split is one of the module procedures that take the pattern as a character: handy once, but a regex compiled once is faster in a loop.
Errors
call re%compile('(\d+', iostat=iostat, iomsg=iomsg)
print '(A,I0,2A)', 'error at byte ', iostat, ': ', trim(iomsg)$ regex_tour
T ann@example.org 10 24
ann example.org
1: ann
2: bob
write to ann at example.org or bob at test.net
a|b|c|
error at byte 5: missing ), unterminated group opened at byte 1A malformed pattern gives the byte where the problem is and what it is.
What you learned
compile, search, group, finditer, sub, re_split. Reference: Regular Expressions.
Next: 8. Unicode text.