-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathstring.erl
3166 lines (2806 loc) · 99.6 KB
/
string.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%% A string library that works on grapheme clusters, with the exception
%% of codepoints of class 'prepend' and non modern (or decomposed) Hangul.
%% If these codepoints appear, functions like 'find/2' may return a string
%% which starts inside a grapheme cluster.
%% These exceptions are made because the codepoints classes are
%% seldom used and require that we are able look at previous codepoints in
%% the stream and is thus hard to implement effectively.
%%
%% GC (grapheme cluster) implies that the length of string 'ß↑e̊' is 3 though
%% it is represented by the codepoints [223,8593,101,778] or the
%% utf8 binary <<195,159,226,134,145,101,204,138>>
%%
%% And that searching for strings or graphemes finds the correct positions:
%%
%% find("eeeee̊eee", "e̊") -> "e̊ee".:
%% find("1£4e̊abcdef", "e") -> "ef"
%%
%% Most functions expect all input to be normalized to one form,
%% see unicode:characters_to_nfc and unicode:characters_to_nfd functions.
%% When appending strings no checking is done to verify that the
%% result is valid unicode strings.
%%
%% The functions may crash for invalid utf-8 input.
%%
%% Return value should be kept consistent when return type is
%% unicode:chardata() i.e. binary input => binary output,
%% list input => list output mixed input => mixed output
%%
-module(string).
-moduledoc """
String processing functions.
This module provides functions for string processing.
A string in this module is represented by `t:unicode:chardata/0`, that is, a
list of codepoints, binaries with UTF-8-encoded codepoints (_UTF-8 binaries_),
or a mix of the two.
```text
"abcd" is a valid string
<<"abcd">> is a valid string
["abcd"] is a valid string
<<"abc..åäö"/utf8>> is a valid string
<<"abc..åäö">> is NOT a valid string,
but a binary with Latin-1-encoded codepoints
[<<"abc">>, "..åäö"] is a valid string
[atom] is NOT a valid string
```
This module operates on grapheme clusters. A _grapheme cluster_ is a
user-perceived character, which can be represented by several codepoints.
```text
"å" [229] or [97, 778]
"e̊" [101, 778]
```
The string length of "ß↑e̊" is 3, even though it is represented by the codepoints
`[223,8593,101,778]` or the UTF-8 binary `<<195,159,226,134,145,101,204,138>>`.
Grapheme clusters for codepoints of class `prepend` and non-modern (or
decomposed) Hangul is not handled for performance reasons in `find/3`,
`replace/3`, `split/2`, `split/3` and `trim/3`.
Splitting and appending strings is to be done on grapheme clusters borders.
There is no verification that the results of appending strings are valid or
normalized.
Most of the functions expect all input to be normalized to one form, see for
example `unicode:characters_to_nfc_list/1`.
Language or locale specific handling of input is not considered in any function.
The functions can crash for non-valid input strings. For example, the functions
expect UTF-8 binaries but not all functions verify that all binaries are encoded
correctly.
Unless otherwise specified the return value type is the same as the input type.
That is, binary input returns binary output, list input returns a list output,
and mixed input can return a mixed output.
```erlang
1> string:trim(" sarah ").
"sarah"
2> string:trim(<<" sarah ">>).
<<"sarah">>
3> string:lexemes("foo bar", " ").
["foo","bar"]
4> string:lexemes(<<"foo bar">>, " ").
[<<"foo">>,<<"bar">>]
```
This module has been reworked in Erlang/OTP 20 to handle `t:unicode:chardata/0`
and operate on grapheme clusters. The
[`old functions`](`m:string#obsolete-api-functions`) that only work on Latin-1
lists as input are still available but should not be used, they will be
deprecated in a future release.
## Notes
Some of the general string functions can seem to overlap each other. The reason
is that this string package is the combination of two earlier packages and all
functions of both packages have been retained.
""".
-moduledoc(#{titles =>
[{function,<<"Functions">>},
{function,<<"Obsolete API functions">>}]}).
-export([is_empty/1, length/1, to_graphemes/1,
reverse/1,
equal/2, equal/3, equal/4,
slice/2, slice/3,
pad/2, pad/3, pad/4, trim/1, trim/2, trim/3, chomp/1,
take/2, take/3, take/4,
lexemes/2, nth_lexeme/3,
uppercase/1, lowercase/1, titlecase/1,casefold/1,
prefix/2,
split/2,split/3,replace/3,replace/4,
find/2,find/3,
jaro_similarity/2,
next_codepoint/1, next_grapheme/1
]).
-export([to_float/1, to_integer/1]).
%% Old (will be deprecated) lists/string API kept for backwards compability
-export([len/1, concat/2, % equal/2, (extended in the new api)
chr/2,rchr/2,str/2,rstr/2,
span/2,cspan/2,substr/2,substr/3, tokens/2,
chars/2,chars/3]).
-export([copies/2,words/1,words/2,strip/1,strip/2,strip/3,
sub_word/2,sub_word/3,left/2,left/3,right/2,right/3,
sub_string/2,sub_string/3,centre/2,centre/3, join/2]).
-export([to_upper/1, to_lower/1]).
%%
-import(lists,[member/2]).
-compile({no_auto_import,[length/1]}).
-compile({inline, [btoken/2, rev/1, append/2, stack/2, search_compile/1]}).
-define(ASCII_LIST(CP1,CP2),
is_integer(CP1), 0 =< CP1, CP1 < 256,
is_integer(CP2), 0 =< CP2, CP2 < 256, CP1 =/= $\r).
-export_type([grapheme_cluster/0]).
-doc "A user-perceived character, consisting of one or more codepoints.".
-type grapheme_cluster() :: char() | [char()].
-type direction() :: 'leading' | 'trailing'.
-dialyzer({no_improper_lists, [stack/2, length_b/3, str_to_map/2]}).
%%% BIFs internal (not documented) should not to be used outside of this module
%%% May be removed
-export([list_to_float/1, list_to_integer/1]).
%% Uses bifs: string:list_to_float/1 and string:list_to_integer/1
-doc false.
-spec list_to_float(String) -> {Float, Rest} | {'error', Reason} when
String :: string(),
Float :: float(),
Rest :: string(),
Reason :: 'no_float' | 'not_a_list'.
list_to_float(_) ->
erlang:nif_error(undef).
-doc false.
-spec list_to_integer(String) -> {Int, Rest} | {'error', Reason} when
String :: string(),
Int :: integer(),
Rest :: string(),
Reason :: 'no_integer' | 'not_a_list'.
list_to_integer(String) ->
Base = 10,
case erts_internal:list_to_integer(String, Base) of
{_, _}=Result ->
Result;
big ->
{Binary, Tail} = split_string(String),
try binary_to_integer(Binary) of
N ->
{N, Tail}
catch
error:system_limit ->
{error, system_limit}
end;
Reason ->
{error, Reason}
end.
split_string([C|Cs]) when C =:= $+; C =:= $- ->
split_string(Cs, [C]);
split_string(Cs) ->
split_string(Cs, []).
split_string([C|Cs], Acc) when is_integer(C), $0 =< C, C =< $9 ->
split_string(Cs, [C|Acc]);
split_string(Cs, Acc) ->
{list_to_binary(lists:reverse(Acc)),Cs}.
%%% End of BIFs
%% Check if string is the empty string
-doc """
Returns `true` if `String` is the empty string, otherwise `false`.
_Example:_
```erlang
1> string:is_empty("foo").
false
2> string:is_empty(["",<<>>]).
true
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec is_empty(String::unicode:chardata()) -> boolean().
is_empty([]) -> true;
is_empty(<<>>) -> true;
is_empty([L|R]) -> is_empty(L) andalso is_empty(R);
is_empty(_) -> false.
%% Count the number of grapheme clusters in chardata
-doc """
Returns the number of grapheme clusters in `String`.
_Example:_
```erlang
1> string:length("ß↑e̊").
3
2> string:length(<<195,159,226,134,145,101,204,138>>).
3
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec length(String::unicode:chardata()) -> non_neg_integer().
length(<<CP1/utf8, Bin/binary>>) ->
length_b(Bin, CP1, 0);
length(CD) ->
length_1(CD, 0).
%% Convert a string to a list of grapheme clusters
-doc """
Converts `String` to a list of grapheme clusters.
_Example:_
```erlang
1> string:to_graphemes("ß↑e̊").
[223,8593,[101,778]]
2> string:to_graphemes(<<"ß↑e̊"/utf8>>).
[223,8593,[101,778]]
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec to_graphemes(String::unicode:chardata()) -> [grapheme_cluster()].
to_graphemes(CD0) ->
case unicode_util:gc(CD0) of
[GC|CD] -> [GC|to_graphemes(CD)];
[] -> [];
{error, Err} -> error({badarg, Err})
end.
%% Compare two strings return boolean, assumes that the input are
%% normalized to same form, see unicode:characters_to_nfX_xxx(..)
-doc(#{equiv => equal(A, B, true)}).
-doc(#{title => <<"Functions">>}).
-spec equal(A, B) -> boolean() when
A::unicode:chardata(),
B::unicode:chardata().
equal(A,B) when is_binary(A), is_binary(B) ->
A =:= B;
equal(A,B) ->
equal_1(A,B).
%% Compare two strings return boolean, assumes that the input are
%% normalized to same form, see unicode:characters_to_nfX_xxx(..)
%% does casefold on the fly
-doc(#{equiv => equal(A, B, IgnoreCase, none)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec equal(A, B, IgnoreCase) -> boolean() when
A::unicode:chardata(),
B::unicode:chardata(),
IgnoreCase :: boolean().
equal(A, B, false) ->
equal(A,B);
equal(A, B, true) ->
equal_nocase(A,B).
%% Compare two strings return boolean
%% if specified does casefold and normalization on the fly
-doc """
Returns `true` if `A` and `B` are equal, otherwise `false`.
If `IgnoreCase` is `true` the function does [`casefold`ing](`casefold/1`) on the
fly before the equality test.
If `Norm` is not `none` the function applies normalization on the fly before the
equality test. There are four available normalization forms:
[`nfc`](`unicode:characters_to_nfc_list/1`),
[`nfd`](`unicode:characters_to_nfd_list/1`),
[`nfkc`](`unicode:characters_to_nfkc_list/1`), and
[`nfkd`](`unicode:characters_to_nfkd_list/1`).
_Example:_
```erlang
1> string:equal("åäö", <<"åäö"/utf8>>).
true
2> string:equal("åäö", unicode:characters_to_nfd_binary("åäö")).
false
3> string:equal("åäö", unicode:characters_to_nfd_binary("ÅÄÖ"), true, nfc).
true
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec equal(A, B, IgnoreCase, Norm) -> boolean() when
A :: unicode:chardata(),
B :: unicode:chardata(),
IgnoreCase :: boolean(),
Norm :: 'none' | 'nfc' | 'nfd' | 'nfkc' | 'nfkd'.
equal(A, B, Case, none) ->
equal(A,B,Case);
equal(A, B, false, Norm) ->
equal_norm(A, B, Norm);
equal(A, B, true, Norm) ->
equal_norm_nocase(A, B, Norm).
%% Reverse grapheme clusters
-doc """
Returns the reverse list of the grapheme clusters in `String`.
_Example:_
```erlang
1> Reverse = string:reverse(unicode:characters_to_nfd_binary("ÅÄÖ")).
[[79,776],[65,776],[65,778]]
2> io:format("~ts~n",[Reverse]).
ÖÄÅ
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec reverse(String::unicode:chardata()) -> [grapheme_cluster()].
reverse(<<CP1/utf8, Rest/binary>>) ->
reverse_b(Rest, CP1, []);
reverse(CD) ->
reverse_1(CD, []).
%% Slice a string and return rest of string
%% Note: counts grapheme_clusters
-doc(#{equiv => slice(String, Length, infinity)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec slice(String, Start) -> Slice when
String::unicode:chardata(),
Start :: non_neg_integer(),
Slice :: unicode:chardata().
slice(CD, N) when is_integer(N), N >= 0 ->
case slice_l0(CD, N) of
[] when is_binary(CD) -> <<>>;
Res -> Res
end.
-doc """
Returns a substring of `String` of at most `Length` grapheme clusters, starting
at position `Start`.
_Example:_
```erlang
1> string:slice(<<"He̊llö Wörld"/utf8>>, 4).
<<"ö Wörld"/utf8>>
2> string:slice(["He̊llö ", <<"Wörld"/utf8>>], 4,4).
"ö Wö"
3> string:slice(["He̊llö ", <<"Wörld"/utf8>>], 4,50).
"ö Wörld"
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec slice(String, Start, Length) -> Slice when
String::unicode:chardata(),
Start :: non_neg_integer(),
Length :: 'infinity' | non_neg_integer(),
Slice :: unicode:chardata().
slice(CD, N, Length)
when is_integer(N), N >= 0, is_integer(Length), Length > 0 ->
case slice_l0(CD, N) of
[] when is_binary(CD) -> <<>>;
L -> slice_trail(L, Length)
end;
slice(CD, N, infinity) when is_integer(N), N >= 0 ->
case slice_l0(CD, N) of
[] when is_binary(CD) -> <<>>;
Res -> Res
end;
slice(CD, _, 0) ->
case is_binary(CD) of
true -> <<>>;
false -> []
end.
%% Pad a string to desired length
-doc(#{equiv => pad(String, Length, trailing)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec pad(String, Length) -> unicode:charlist() when
String ::unicode:chardata(),
Length :: integer().
pad(CD, Length) ->
pad(CD, Length, trailing, $\s).
-doc(#{equiv => pad(String, Length, Dir, $\s)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec pad(String, Length, Dir) -> unicode:charlist() when
String ::unicode:chardata(),
Length :: integer(),
Dir :: direction() | 'both'.
pad(CD, Length, Dir) ->
pad(CD, Length, Dir, $\s).
-doc """
Pads `String` to `Length` with grapheme cluster `Char`. `Dir`, which can be
`leading`, `trailing`, or `both`, indicates where the padding should be added.
_Example:_
```erlang
1> string:pad(<<"He̊llö"/utf8>>, 8).
[<<72,101,204,138,108,108,195,182>>,32,32,32]
2> io:format("'~ts'~n",[string:pad("He̊llö", 8, leading)]).
' He̊llö'
3> io:format("'~ts'~n",[string:pad("He̊llö", 8, both)]).
' He̊llö '
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec pad(String, Length, Dir, Char) -> unicode:charlist() when
String ::unicode:chardata(),
Length :: integer(),
Dir :: direction() | 'both',
Char :: grapheme_cluster().
pad(CD, Length, leading, Char) when is_integer(Length) ->
Len = length(CD),
[lists:duplicate(max(0, Length-Len), Char), CD];
pad(CD, Length, trailing, Char) when is_integer(Length) ->
Len = length(CD),
[CD|lists:duplicate(max(0, Length-Len), Char)];
pad(CD, Length, both, Char) when is_integer(Length) ->
Len = length(CD),
Size = max(0, Length-Len),
Pre = lists:duplicate(Size div 2, Char),
Post = case Size rem 2 of
1 -> [Char];
_ -> []
end,
[Pre, CD, Pre|Post].
%% Strip characters from whitespace or Separator in Direction
-doc(#{equiv => trim(String, both)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec trim(String) -> unicode:chardata() when
String :: unicode:chardata().
trim(Str) ->
trim(Str, both, unicode_util:whitespace()).
-doc """
Equivalent to [`trim(String, Dir, Whitespace})`](`trim/3`) where
`Whitespace` is the set of nonbreakable whitespace codepoints, defined
as Pattern_White_Space in
[Unicode Standard Annex #31](http://unicode.org/reports/tr31/).
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec trim(String, Dir) -> unicode:chardata() when
String :: unicode:chardata(),
Dir :: direction() | 'both'.
trim(Str, Dir) ->
trim(Str, Dir, unicode_util:whitespace()).
-doc """
Returns a string, where leading or trailing, or both, `Characters` have been
removed.
`Dir` which can be `leading`, `trailing`, or `both`, indicates from
which direction characters are to be removed.
Note that `[$\r,$\n]` is one grapheme cluster according to the Unicode
Standard.
_Example:_
```erlang
1> string:trim("\t Hello \n").
"Hello"
2> string:trim(<<"\t Hello \n">>, leading).
<<"Hello \n">>
3> string:trim(<<".Hello.\n">>, trailing, "\n.").
<<".Hello">>
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec trim(String, Dir, Characters) -> unicode:chardata() when
String :: unicode:chardata(),
Dir :: direction() | 'both',
Characters :: [grapheme_cluster()].
trim(Str, _, []) -> Str;
trim(Str, leading, [Sep])
when is_list(Str), is_integer(Sep), 0 =< Sep, Sep < 256 ->
trim_ls(Str, Sep);
trim(Str, leading, Sep) when is_list(Sep) ->
trim_l(Str, Sep);
trim(Str, trailing, [Sep])
when is_list(Str), is_integer(Sep), 0 =< Sep, Sep < 256 ->
trim_ts(Str, Sep);
trim(Str, trailing, Seps0) when is_list(Seps0) ->
Seps = search_pattern(Seps0),
trim_t(Str, 0, Seps);
trim(Str, both, Sep) when is_list(Sep) ->
trim(trim(Str,leading,Sep), trailing, Sep).
%% Delete trailing newlines or \r\n
-doc """
Returns a string where any trailing `\n` or `\r\n` have been removed from
`String`.
_Example:_
```erlang
182> string:chomp(<<"\nHello\n\n">>).
<<"\nHello">>
183> string:chomp("\nHello\r\r\n").
"\nHello\r"
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec chomp(String::unicode:chardata()) -> unicode:chardata().
chomp(Str) ->
trim(Str, trailing, [[$\r,$\n],$\n]).
%% Split String into two parts where the leading part consists of Characters
-doc(#{equiv => take(String, Characters, false)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec take(String, Characters) -> {Leading, Trailing} when
String::unicode:chardata(),
Characters::[grapheme_cluster()],
Leading::unicode:chardata(),
Trailing::unicode:chardata().
take(Str, Sep) ->
take(Str, Sep, false, leading).
-doc(#{equiv => take(String, Characters, Complement, leading)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec take(String, Characters, Complement) -> {Leading, Trailing} when
String::unicode:chardata(),
Characters::[grapheme_cluster()],
Complement::boolean(),
Leading::unicode:chardata(),
Trailing::unicode:chardata().
take(Str, Sep, Complement) ->
take(Str, Sep, Complement, leading).
-doc """
Takes characters from `String` as long as the characters are members of set
`Characters` or the complement of set `Characters`. `Dir`, which can be
`leading` or `trailing`, indicates from which direction characters are to be
taken.
_Example:_
```erlang
5> string:take("abc0z123", lists:seq($a,$z)).
{"abc","0z123"}
6> string:take(<<"abc0z123">>, lists:seq($0,$9), true, leading).
{<<"abc">>,<<"0z123">>}
7> string:take("abc0z123", lists:seq($0,$9), false, trailing).
{"abc0z","123"}
8> string:take(<<"abc0z123">>, lists:seq($a,$z), true, trailing).
{<<"abc0z">>,<<"123">>}
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec take(String, Characters, Complement, Dir) -> {Leading, Trailing} when
String::unicode:chardata(),
Characters::[grapheme_cluster()],
Complement::boolean(),
Dir::direction(),
Leading::unicode:chardata(),
Trailing::unicode:chardata().
take(Str, [], Complement, Dir) ->
Empty = case is_binary(Str) of true -> <<>>; false -> [] end,
case {Complement,Dir} of
{false, leading} -> {Empty, Str};
{false, trailing} -> {Str, Empty};
{true, leading} -> {Str, Empty};
{true, trailing} -> {Empty, Str}
end;
take(Str, Sep, false, leading) ->
take_l(Str, Sep, []);
take(Str, Sep0, true, leading) ->
Sep = search_pattern(Sep0),
take_lc(Str, Sep, []);
take(Str, Sep0, false, trailing) ->
Sep = search_pattern(Sep0),
take_t(Str, 0, Sep);
take(Str, Sep0, true, trailing) ->
Sep = search_pattern(Sep0),
take_tc(Str, 0, Sep).
%% Uppercase all chars in Str
-doc """
Converts `String` to uppercase.
See also `titlecase/1`.
_Example:_
```erlang
1> string:uppercase("Michał").
"MICHAŁ"
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec uppercase(String::unicode:chardata()) -> unicode:chardata().
uppercase(CD) when is_list(CD) ->
try uppercase_list(CD, false)
catch unchanged -> CD
end;
uppercase(<<CP1/utf8, Rest/binary>>=Orig) ->
try uppercase_bin(CP1, Rest, false) of
List -> unicode:characters_to_binary(List)
catch unchanged -> Orig
end;
uppercase(<<>>) ->
<<>>;
uppercase(Bin) ->
error({badarg, Bin}).
%% Lowercase all chars in Str
-doc """
Converts `String` to lowercase.
Notice that function `casefold/1` should be used when converting a string to be
tested for equality.
_Example:_
```erlang
2> string:lowercase(string:uppercase("Michał")).
"michał"
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec lowercase(String::unicode:chardata()) -> unicode:chardata().
lowercase(CD) when is_list(CD) ->
try lowercase_list(CD, false)
catch unchanged -> CD
end;
lowercase(<<CP1/utf8, Rest/binary>>=Orig) ->
try lowercase_bin(CP1, Rest, false) of
List -> unicode:characters_to_binary(List)
catch unchanged -> Orig
end;
lowercase(<<>>) ->
<<>>;
lowercase(Bin) ->
error({badarg, Bin}).
%% Make a titlecase of the first char in Str
-doc """
Converts `String` to titlecase.
_Example:_
```erlang
1> string:titlecase("ß is a SHARP s").
"Ss is a SHARP s"
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec titlecase(String::unicode:chardata()) -> unicode:chardata().
titlecase(CD) when is_list(CD) ->
case unicode_util:titlecase(CD) of
[GC|Tail] -> append(GC,Tail);
Empty -> Empty
end;
titlecase(CD) when is_binary(CD) ->
case unicode_util:titlecase(CD) of
[CP|Chars] when is_integer(CP) -> <<CP/utf8,Chars/binary>>;
[CPs|Chars] ->
<< << <<CP/utf8>> || CP <- CPs>>/binary, Chars/binary>>;
[] -> <<>>
end.
%% Make a comparable string of the Str should be used for equality tests only
-doc """
Converts `String` to a case-agnostic comparable string. Function
[`casefold/1`](`casefold/1`) is preferred over [`lowercase/1`](`lowercase/1`)
when two strings are to be compared for equality. See also `equal/4`.
_Example:_
```erlang
1> string:casefold("Ω and ẞ SHARP S").
"ω and ss sharp s"
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec casefold(String::unicode:chardata()) -> unicode:chardata().
casefold(CD) when is_list(CD) ->
try casefold_list(CD, false)
catch unchanged -> CD
end;
casefold(<<CP1/utf8, Rest/binary>>=Orig) ->
try casefold_bin(CP1, Rest, false) of
List -> unicode:characters_to_binary(List)
catch unchanged -> Orig
end;
casefold(<<>>) ->
<<>>;
casefold(Bin) ->
error({badarg, Bin}).
-doc """
Argument `String` is expected to start with a valid text represented integer
(the digits are ASCII values). Remaining characters in the string after the
integer are returned in `Rest`.
_Example:_
```erlang
1> {I1,Is} = string:to_integer("33+22"),
1> {I2,[]} = string:to_integer(Is),
1> I1-I2.
11
2> string:to_integer("0.5").
{0,".5"}
3> string:to_integer("x=2").
{error,no_integer}
```
""".
-doc(#{title => <<"Functions">>}).
-spec to_integer(String) -> {Int, Rest} | {'error', Reason} when
String :: unicode:chardata(),
Int :: integer(),
Rest :: unicode:chardata(),
Reason :: 'no_integer' | badarg.
to_integer(String) ->
try take(String, "+-0123456789") of
{Head, Tail} ->
case is_empty(Head) of
true -> {error, no_integer};
false ->
List = unicode:characters_to_list(Head),
case string:list_to_integer(List) of
{error, _} = Err -> Err;
{Int, Rest} ->
to_number(String, Int, Rest, List, Tail)
end
end
catch _:_ -> {error, badarg}
end.
-doc """
Argument `String` is expected to start with a valid text represented float (the
digits are ASCII values). Remaining characters in the string after the float are
returned in `Rest`.
_Example:_
```erlang
1> {F1,Fs} = string:to_float("1.0-1.0e-1"),
1> {F2,[]} = string:to_float(Fs),
1> F1+F2.
0.9
2> string:to_float("3/2=1.5").
{error,no_float}
3> string:to_float("-1.5eX").
{-1.5,"eX"}
```
""".
-doc(#{title => <<"Functions">>}).
-spec to_float(String) -> {Float, Rest} | {'error', Reason} when
String :: unicode:chardata(),
Float :: float(),
Rest :: unicode:chardata(),
Reason :: 'no_float' | 'badarg'.
to_float(String) ->
try take(String, "+-0123456789eE.,") of
{Head, Tail} ->
case is_empty(Head) of
true -> {error, no_float};
false ->
List = unicode:characters_to_list(Head),
case string:list_to_float(List) of
{error, _} = Err -> Err;
{Float, Rest} ->
to_number(String, Float, Rest, List, Tail)
end
end
catch _:_ -> {error, badarg}
end.
to_number(String, Number, Rest, List, _Tail) when is_binary(String) ->
BSz = erlang:length(List)-erlang:length(Rest),
<<_:BSz/binary, Cont/binary>> = String,
{Number, Cont};
to_number(_, Number, Rest, _, Tail) ->
{Number, concat(Rest,Tail)}.
%% Return the remaining string with prefix removed or else nomatch
-doc """
If `Prefix` is the prefix of `String`, removes it and returns the remainder of
`String`, otherwise returns `nomatch`.
_Example:_
```erlang
1> string:prefix(<<"prefix of string">>, "pre").
<<"fix of string">>
2> string:prefix("pre", "prefix").
nomatch
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec prefix(String::unicode:chardata(), Prefix::unicode:chardata()) ->
'nomatch' | unicode:chardata().
prefix(Str, Prefix0) ->
Result = case unicode:characters_to_list(Prefix0) of
[] -> Str;
Prefix -> prefix_1(Str, Prefix)
end,
case Result of
[] when is_binary(Str) -> <<>>;
Res -> Res
end.
%% split String with the first occurrence of SearchPattern, return list of splits
-doc(#{equiv => split(String, SearchPattern, leading)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec split(String, SearchPattern) -> [unicode:chardata()] when
String :: unicode:chardata(),
SearchPattern :: unicode:chardata().
split(String, SearchPattern) ->
split(String, SearchPattern, leading).
%% split String with SearchPattern, return list of splits
-doc """
Splits `String` where `SearchPattern` is encountered and return the remaining
parts. `Where`, default `leading`, indicates whether the `leading`, the
`trailing` or `all` encounters of `SearchPattern` will split `String`.
_Example:_
```erlang
0> string:split("ab..bc..cd", "..").
["ab","bc..cd"]
1> string:split(<<"ab..bc..cd">>, "..", trailing).
[<<"ab..bc">>,<<"cd">>]
2> string:split(<<"ab..bc....cd">>, "..", all).
[<<"ab">>,<<"bc">>,<<>>,<<"cd">>]
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec split(String, SearchPattern, Where) -> [unicode:chardata()] when
String :: unicode:chardata(),
SearchPattern :: unicode:chardata(),
Where :: direction() | 'all'.
split(String, SearchPattern, Where) ->
case is_empty(SearchPattern) of
true -> [String];
false ->
SearchPatternCPs = unicode:characters_to_list(SearchPattern),
case split_1(String, SearchPatternCPs, 0, Where, [], []) of
{_Curr, []} -> [String];
{_Curr, Acc} when Where =:= trailing -> Acc;
{Curr, Acc} when Where =:= all -> lists:reverse([Curr|Acc]);
Acc when is_list(Acc) -> Acc
end
end.
%% Replace the first SearchPattern in String with Replacement
-doc(#{equiv => replace(String, SearchPattern, Replacement, leading)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec replace(String, SearchPattern, Replacement) ->
[unicode:chardata()] when
String :: unicode:chardata(),
SearchPattern :: unicode:chardata(),
Replacement :: unicode:chardata().
replace(String, SearchPattern, Replacement) ->
lists:join(Replacement, split(String, SearchPattern)).
%% Replace Where SearchPattern in String with Replacement
-doc """
Replaces `SearchPattern` in `String` with `Replacement`. `Where`, indicates whether
the `leading`, the `trailing` or `all` encounters of `SearchPattern` are to be replaced.
Can be implemented as:
```erlang
lists:join(Replacement, split(String, SearchPattern, Where)).
```
_Example:_
```erlang
1> string:replace(<<"ab..cd..ef">>, "..", "*").
[<<"ab">>,"*",<<"cd..ef">>]
2> string:replace(<<"ab..cd..ef">>, "..", "*", all).
[<<"ab">>,"*",<<"cd">>,"*",<<"ef">>]
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec replace(String, SearchPattern, Replacement, Where) ->
[unicode:chardata()] when
String :: unicode:chardata(),
SearchPattern :: unicode:chardata(),
Replacement :: unicode:chardata(),
Where :: direction() | 'all'.
replace(String, SearchPattern, Replacement, Where) ->
lists:join(Replacement, split(String, SearchPattern, Where)).
%% Split Str into a list of chardata separated by one of the grapheme
%% clusters in Seps
-doc """
Returns a list of lexemes in `String`, separated by the grapheme clusters in
`SeparatorList`.
Notice that, as shown in this example, two or more adjacent separator graphemes
clusters in `String` are treated as one. That is, there are no empty strings in
the resulting list of lexemes. See also `split/3` which returns empty strings.
Notice that `[$\r,$\n]` is one grapheme cluster.
_Example:_
```erlang
1> string:lexemes("abc de̊fxxghix jkl\r\nfoo", "x e" ++ [[$\r,$\n]]).
["abc","de̊f","ghi","jkl","foo"]
2> string:lexemes(<<"abc de̊fxxghix jkl\r\nfoo"/utf8>>, "x e" ++ [$\r,$\n]).
[<<"abc">>,<<"de̊f"/utf8>>,<<"ghi">>,<<"jkl\r\nfoo">>]
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec lexemes(String::unicode:chardata(),
SeparatorList::[grapheme_cluster()]) ->
[unicode:chardata()].
lexemes([], _) -> [];
lexemes(Str, []) -> [Str];
lexemes(Str, Seps0) when is_list(Seps0) ->
Seps = search_pattern(Seps0),
lexemes_m(Str, Seps, []).
-doc """
Returns lexeme number `N` in `String`, where lexemes are separated by the
grapheme clusters in `SeparatorList`.
_Example:_
```erlang
1> string:nth_lexeme("abc.de̊f.ghiejkl", 3, ".e").
"ghi"
```
""".
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec nth_lexeme(String, N, SeparatorList) -> unicode:chardata() when
String::unicode:chardata(),
N::non_neg_integer(),
SeparatorList::[grapheme_cluster()].
nth_lexeme(Str, 1, []) -> Str;
nth_lexeme(Str, N, Seps0) when is_list(Seps0), is_integer(N), N > 0 ->
Seps = search_pattern(Seps0),
nth_lexeme_m(Str, Seps, N).
%% find first SearchPattern in String return rest of string
-doc(#{equiv => find(String, SearchPattern, leading)}).
-doc(#{title => <<"Functions">>,since => <<"OTP 20.0">>}).
-spec find(String, SearchPattern) -> unicode:chardata() | 'nomatch' when
String::unicode:chardata(),
SearchPattern::unicode:chardata().
find(String, SearchPattern) ->
find(String, SearchPattern, leading).