| Did you know ... | Search Documentation: |
| Predicate sub_atom/5 |
Pick out a sub-atom of length 3 starting a 0-based index 2:
?- sub_atom(aaxyzbbb, 2, 3, After, SubAtom). After = 3, SubAtom = xyz.
The following example splits a string of the form <name>=<value> into the name part (an atom) and the value (a string).
name_value(String, Name, Value) :-
sub_atom(String, Before, _, After, "="),
!,
sub_atom(String, 0, Before, _, Name),
sub_atom(String, _, After, 0, Value).
This example defines a predicate that inserts a value at a position. Note that sub_string/5 is used here instead of sub_atom/5 to avoid the overhead of creating atoms for the intermediate results.
atom_insert(Str, Val, At, NewStr) :-
sub_string(Str, 0, At, A1, S1),
sub_string(Str, At, A1, _, S2),
atomic_list_concat([S1,Val,S2], NewStr).
On backtracking, matches are delivered in order left-to-right (i.e. Before increases monotonically):
?- sub_atom('xATGATGAxATGAxATGAx', Before, Length, After, 'ATGA').
Before = 1, Length = 4, After = 14 ;
Before = Length, Length = 4, After = 11 ;
Before = 9, Length = 4, After = 6 ;
Before = 14, Length = 4, After = 1 ;
false.
See also sub_string/5, the corresponding predicate for SWI-Prolog strings.
To enumerate the 0-based starting indices of a possibly overlapping sub-atom:
?- sub_atom(banana, Pos, _, _, ana). Pos = 1 ; Pos = 3 ; false.
Another example
% split username from email account
email_user(Email,User):-
sub_atom(Email,U,1,A,'@'),
T is A+1,
sub_atom(Email,U,T,_,Tail),
atom_concat(User,Tail,Email),!.
:- email_user('john@mail.com',User)
U = 'john'
check that suffix is '.bar': sub_atom('foo.bar', _, _, 0, '.bar').
faster version of removing a suffix suffix (same as atom_concat(Start, Suffix, Atom) if Suffix is ground:
sub_atom(Atom, Before, _, 0, Suffix), Before0 is Before - 1, sub_atom(Atom, 0, Before0, _, Start)
Strip off a prefix, e.g., '/' (from an absolute file name):
?- Str='/abc/def', sub_atom(Str, 0, _, After, '/'), sub_atom(Str, 1, After, 0, Sub). Str = '/abc/def', After = 7, Sub = 'abc/def'.
This is equivalent to:
?- Str='/abc/def',
atom_concat('/', Sub, Str).
Str = '/abc/def',
Sub = 'abc/def'.
A useful example is:
?- sub_atom('123456789', Before, Len, After, '3').
Before = 2,
Len = 1,
After = 6 .