-
-
Notifications
You must be signed in to change notification settings - Fork 205
Expand file tree
/
Copy pathstrings.py
More file actions
3143 lines (2503 loc) · 94.7 KB
/
strings.py
File metadata and controls
3143 lines (2503 loc) · 94.7 KB
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
# -*- coding: utf-8 -*-
"""
Strings and Characters
"""
import io
import re
import sys
from sys import version_info
import unicodedata
from binascii import hexlify, unhexlify
from heapq import heappush, heappop
from typing import Callable
from mathics.version import __version__ # noqa used in loading to check consistency.
from mathics.builtin.base import BinaryOperator, Builtin, Test, Predefined
from mathics.core.expression import (
Expression,
Symbol,
SymbolFailed,
SymbolFalse,
SymbolTrue,
String,
Integer,
from_python,
string_list,
)
from mathics.core.parser import MathicsFileLineFeeder, parse
from mathics.builtin.lists import python_seq, convert_seq
from mathics.settings import SYSTEM_CHARACTER_ENCODING
from mathics_scanner import TranslateError
_regex_longest = {
"+": "+",
"*": "*",
}
_regex_shortest = {
"+": "+?",
"*": "*?",
}
def _encode_pname(name):
return "n" + hexlify(name.encode("utf8")).decode("utf8")
def _decode_pname(name):
return unhexlify(name[1:]).decode("utf8")
def _evaluate_match(s, m, evaluation):
replace = dict(
(_decode_pname(name), String(value)) for name, value in m.groupdict().items()
)
return s.replace_vars(replace, in_scoping=False).evaluate(evaluation)
def _parallel_match(text, rules, flags, limit):
heap = []
def push(i, iter, form):
m = None
try:
m = next(iter)
except StopIteration:
pass
if m is not None:
heappush(heap, (m.start(), i, m, form, iter))
for i, (patt, form) in enumerate(rules):
push(i, re.finditer(patt, text, flags=flags), form)
k = 0
n = 0
while heap:
start, i, match, form, iter = heappop(heap)
if start >= k:
yield match, form
n += 1
if n >= limit > 0:
break
k = match.end()
push(i, iter, form)
def to_regex(
expr, evaluation, q=_regex_longest, groups=None, abbreviated_patterns=False
):
if expr is None:
return None
if groups is None:
groups = {}
def recurse(x, quantifiers=q):
return to_regex(x, evaluation, q=quantifiers, groups=groups)
if isinstance(expr, String):
result = expr.get_string_value()
if abbreviated_patterns:
pieces = []
i, j = 0, 0
while j < len(result):
c = result[j]
if c == "\\" and j + 1 < len(result):
pieces.append(re.escape(result[i:j]))
pieces.append(re.escape(result[j + 1]))
j += 2
i = j
elif c == "*":
pieces.append(re.escape(result[i:j]))
pieces.append("(.*)")
j += 1
i = j
elif c == "@":
pieces.append(re.escape(result[i:j]))
# one or more characters, excluding uppercase letters
pieces.append("([^A-Z]+)")
j += 1
i = j
else:
j += 1
pieces.append(re.escape(result[i:j]))
result = "".join(pieces)
else:
result = re.escape(result)
return result
if expr.has_form("RegularExpression", 1):
regex = expr.leaves[0].get_string_value()
if regex is None:
return regex
try:
re.compile(regex)
# Don't return the compiled regex because it may need to composed
# further e.g. StringExpression["abc", RegularExpression[regex2]].
return regex
except re.error:
return None # invalid regex
if isinstance(expr, Symbol):
return {
"System`NumberString": r"[-|+]?(\d+(\.\d*)?|\.\d+)?",
"System`Whitespace": r"(?u)\s+",
"System`DigitCharacter": r"\d",
"System`WhitespaceCharacter": r"(?u)\s",
"System`WordCharacter": r"(?u)[^\W_]",
"System`StartOfLine": r"^",
"System`EndOfLine": r"$",
"System`StartOfString": r"\A",
"System`EndOfString": r"\Z",
"System`WordBoundary": r"\b",
"System`LetterCharacter": r"(?u)[^\W_0-9]",
"System`HexidecimalCharacter": r"[0-9a-fA-F]",
}.get(expr.get_name())
if expr.has_form("CharacterRange", 2):
(start, stop) = (leaf.get_string_value() for leaf in expr.leaves)
if all(x is not None and len(x) == 1 for x in (start, stop)):
return "[{0}-{1}]".format(re.escape(start), re.escape(stop))
if expr.has_form("Blank", 0):
return r"(.|\n)"
if expr.has_form("BlankSequence", 0):
return r"(.|\n)" + q["+"]
if expr.has_form("BlankNullSequence", 0):
return r"(.|\n)" + q["*"]
if expr.has_form("Except", 1, 2):
if len(expr.leaves) == 1:
leaves = [expr.leaves[0], Expression("Blank")]
else:
leaves = [expr.leaves[0], expr.leaves[1]]
leaves = [recurse(leaf) for leaf in leaves]
if all(leaf is not None for leaf in leaves):
return "(?!{0}){1}".format(*leaves)
if expr.has_form("Characters", 1):
leaf = expr.leaves[0].get_string_value()
if leaf is not None:
return "[{0}]".format(re.escape(leaf))
if expr.has_form("StringExpression", None):
leaves = [recurse(leaf) for leaf in expr.leaves]
if None in leaves:
return None
return "".join(leaves)
if expr.has_form("Repeated", 1):
leaf = recurse(expr.leaves[0])
if leaf is not None:
return "({0})".format(leaf) + q["+"]
if expr.has_form("RepeatedNull", 1):
leaf = recurse(expr.leaves[0])
if leaf is not None:
return "({0})".format(leaf) + q["*"]
if expr.has_form("Alternatives", None):
leaves = [recurse(leaf) for leaf in expr.leaves]
if all(leaf is not None for leaf in leaves):
return "|".join(leaves)
if expr.has_form("Shortest", 1):
return recurse(expr.leaves[0], quantifiers=_regex_shortest)
if expr.has_form("Longest", 1):
return recurse(expr.leaves[0], quantifiers=_regex_longest)
if expr.has_form("Pattern", 2) and isinstance(expr.leaves[0], Symbol):
name = expr.leaves[0].get_name()
patt = groups.get(name, None)
if patt is not None:
if expr.leaves[1].has_form("Blank", 0):
pass # ok, no warnings
elif not expr.leaves[1].sameQ(patt):
evaluation.message(
"StringExpression", "cond", expr.leaves[0], expr, expr.leaves[0]
)
return "(?P=%s)" % _encode_pname(name)
else:
groups[name] = expr.leaves[1]
return "(?P<%s>%s)" % (_encode_pname(name), recurse(expr.leaves[1]))
return None
def anchor_pattern(patt):
"""
anchors a regex in order to force matching against an entire string.
"""
if not patt.endswith(r"\Z"):
patt = patt + r"\Z"
if not patt.startswith(r"\A"):
patt = r"\A" + patt
return patt
def mathics_split(patt, string, flags):
"""
Python's re.split includes the text of groups if they are capturing.
Furthermore, you can't split on empty matches. Trying to do this returns
the original string for Python < 3.5, raises a ValueError for
Python >= 3.5, <= X and works as expected for Python >= X, where 'X' is
some future version of Python (> 3.6).
For these reasons we implement our own split.
"""
# (start, end) indices of splits
indices = list((m.start(), m.end()) for m in re.finditer(patt, string, flags))
# (start, end) indices of stuff to keep
indices = [(None, 0)] + indices + [(len(string), None)]
indices = [(indices[i][1], indices[i + 1][0]) for i in range(len(indices) - 1)]
# slice up the string
return [string[start:stop] for start, stop in indices]
if version_info >= (3, 0):
def pack_bytes(codes):
return bytes(codes)
def unpack_bytes(codes):
return [int(code) for code in codes]
else:
from struct import pack, unpack
def pack_bytes(codes):
return pack("B" * len(codes), *codes)
def unpack_bytes(codes):
return unpack("B" * len(codes), codes)
class SystemCharacterEncoding(Predefined):
"""
<dl>
<dt>$SystemCharacterEncoding
</dl>
"""
name = "$SystemCharacterEncoding"
rules = {
"$SystemCharacterEncoding": '"' + SYSTEM_CHARACTER_ENCODING + '"',
}
class CharacterEncoding(Predefined):
"""
<dl>
<dt>'CharacterEncoding'
<dd>specifies the default character encoding to use if no other encoding is
specified.
</dl>
"""
name = "$CharacterEncoding"
value = '"UTF-8"'
rules = {
"$CharacterEncoding": value,
}
_encodings = {
# see https://docs.python.org/2/library/codecs.html#standard-encodings
"ASCII": "ascii",
"CP949": "cp949",
"CP950": "cp950",
"EUC-JP": "euc_jp",
"IBM-850": "cp850",
"ISOLatin1": "iso8859_1",
"ISOLatin2": "iso8859_2",
"ISOLatin3": "iso8859_3",
"ISOLatin4": "iso8859_4",
"ISOLatinCyrillic": "iso8859_5",
"ISO8859-1": "iso8859_1",
"ISO8859-2": "iso8859_2",
"ISO8859-3": "iso8859_3",
"ISO8859-4": "iso8859_4",
"ISO8859-5": "iso8859_5",
"ISO8859-6": "iso8859_6",
"ISO8859-7": "iso8859_7",
"ISO8859-8": "iso8859_8",
"ISO8859-9": "iso8859_9",
"ISO8859-10": "iso8859_10",
"ISO8859-13": "iso8859_13",
"ISO8859-14": "iso8859_14",
"ISO8859-15": "iso8859_15",
"ISO8859-16": "iso8859_16",
"koi8-r": "koi8_r",
"MacintoshCyrillic": "mac_cyrillic",
"MacintoshGreek": "mac_greek",
"MacintoshIcelandic": "mac_iceland",
"MacintoshRoman": "mac_roman",
"MacintoshTurkish": "mac_turkish",
"ShiftJIS": "shift_jis",
"Unicode": "utf_16",
"UTF-8": "utf_8",
"UTF8": "utf_8",
"WindowsANSI": "cp1252",
"WindowsBaltic": "cp1257",
"WindowsCyrillic": "cp1251",
"WindowsEastEurope": "cp1250",
"WindowsGreek": "cp1253",
"WindowsTurkish": "cp1254",
}
def to_python_encoding(encoding):
return _encodings.get(encoding)
class CharacterEncodings(Predefined):
name = "$CharacterEncodings"
value = "{%s}" % ",".join(map(lambda s: '"%s"' % s, _encodings.keys()))
rules = {
"$CharacterEncodings": value,
}
class StringExpression(BinaryOperator):
"""
<dl>
<dt>'StringExpression[s_1, s_2, ...]'
<dd>represents a sequence of strings and symbolic string objects $s_i$.
</dl>
>> "a" ~~ "b" // FullForm
= "ab"
#> "a" ~~ "b" ~~ "c" // FullForm
= "abc"
#> a ~~ b
= a ~~ b
"""
operator = "~~"
precedence = 135
attributes = ("Flat", "OneIdentity", "Protected")
messages = {
"invld": "Element `1` is not a valid string or pattern element in `2`.",
"cond": "Ignored restriction given for `1` in `2` as it does not match previous occurences of `1`.",
}
def apply(self, args, evaluation):
"StringExpression[args__String]"
args = args.get_sequence()
args = [arg.get_string_value() for arg in args]
if None in args:
return
return String("".join(args))
class RegularExpression(Builtin):
r"""
<dl>
<dt>'RegularExpression["regex"]'
<dd>represents the regex specified by the string $"regex"$.
</dl>
>> StringSplit["1.23, 4.56 7.89", RegularExpression["(\\s|,)+"]]
= {1.23, 4.56, 7.89}
#> RegularExpression["[abc]"]
= RegularExpression[[abc]]
## Mathematica doesn't seem to verify the correctness of regex
#> StringSplit["ab23c", RegularExpression["[0-9]++"]]
: Element RegularExpression[[0-9]++] is not a valid string or pattern element in RegularExpression[[0-9]++].
= StringSplit[ab23c, RegularExpression[[0-9]++]]
#> StringSplit["ab23c", RegularExpression[2]]
: Element RegularExpression[2] is not a valid string or pattern element in RegularExpression[2].
= StringSplit[ab23c, RegularExpression[2]]
"""
class NumberString(Builtin):
"""
<dl>
<dt>'NumberString'
<dd>represents the characters in a number.
</dl>
>> StringMatchQ["1234", NumberString]
= True
>> StringMatchQ["1234.5", NumberString]
= True
>> StringMatchQ["1.2`20", NumberString]
= False
#> StringMatchQ[".12", NumberString]
= True
#> StringMatchQ["12.", NumberString]
= True
#> StringMatchQ["12.31.31", NumberString]
= False
#> StringMatchQ[".", NumberString]
= False
#> StringMatchQ["-1.23", NumberString]
= True
#> StringMatchQ["+12.3", NumberString]
= True
#> StringMatchQ["+.2", NumberString]
= True
#> StringMatchQ["1.2e4", NumberString]
= False
"""
class DigitCharacter(Builtin):
"""
<dl>
<dt>'DigitCharacter'
<dd>represents the digits 0-9.
</dl>
>> StringMatchQ["1", DigitCharacter]
= True
>> StringMatchQ["a", DigitCharacter]
= False
>> StringMatchQ["12", DigitCharacter]
= False
>> StringMatchQ["123245", DigitCharacter..]
= True
#> StringMatchQ["123245a6", DigitCharacter..]
= False
"""
class Whitespace(Builtin):
r"""
<dl>
<dt>'Whitespace'
<dd>represents a sequence of whitespace characters.
</dl>
>> StringMatchQ["\r \n", Whitespace]
= True
>> StringSplit["a \n b \r\n c d", Whitespace]
= {a, b, c, d}
>> StringReplace[" this has leading and trailing whitespace \n ", (StartOfString ~~ Whitespace) | (Whitespace ~~ EndOfString) -> ""] <> " removed" // FullForm
= "this has leading and trailing whitespace removed"
"""
class WhitespaceCharacter(Builtin):
r"""
<dl>
<dt>'WhitespaceCharacter'
<dd>represents a single whitespace character.
</dl>
>> StringMatchQ["\n", WhitespaceCharacter]
= True
>> StringSplit["a\nb\r\nc\rd", WhitespaceCharacter]
= {a, b, c, d}
For sequences of whitespace characters use 'Whitespace':
>> StringMatchQ[" \n", WhitespaceCharacter]
= False
>> StringMatchQ[" \n", Whitespace]
= True
"""
class WordCharacter(Builtin):
r"""
<dl>
<dt>'WordCharacter'
<dd>represents a single letter or digit character.
</dl>
>> StringMatchQ[#, WordCharacter] &/@ {"1", "a", "A", ",", " "}
= {True, True, True, False, False}
Test whether a string is alphanumeric:
>> StringMatchQ["abc123DEF", WordCharacter..]
= True
>> StringMatchQ["$b;123", WordCharacter..]
= False
"""
class StartOfString(Builtin):
r"""
<dl>
<dt>'StartOfString'
<dd>represents the start of a string.
</dl>
Test whether strings start with "a":
>> StringMatchQ[#, StartOfString ~~ "a" ~~ __] &/@ {"apple", "banana", "artichoke"}
= {True, False, True}
>> StringReplace["aba\nabb", StartOfString ~~ "a" -> "c"]
= cba
. abb
"""
class EndOfString(Builtin):
r"""
<dl>
<dt>'EndOfString'
<dd>represents the end of a string.
</dl>
Test whether strings end with "e":
>> StringMatchQ[#, __ ~~ "e" ~~ EndOfString] &/@ {"apple", "banana", "artichoke"}
= {True, False, True}
>> StringReplace["aab\nabb", "b" ~~ EndOfString -> "c"]
= aab
. abc
"""
class StartOfLine(Builtin):
r"""
<dl>
<dt>'StartOfString'
<dd>represents the start of a line in a string.
</dl>
>> StringReplace["aba\nbba\na\nab", StartOfLine ~~ "a" -> "c"]
= cba
. bba
. c
. cb
>> StringSplit["abc\ndef\nhij", StartOfLine]
= {abc
. , def
. , hij}
"""
class EndOfLine(Builtin):
r"""
<dl>
<dt>'EndOfString'
<dd>represents the end of a line in a string.
</dl>
>> StringReplace["aba\nbba\na\nab", "a" ~~ EndOfLine -> "c"]
= abc
. bbc
. c
. ab
>> StringSplit["abc\ndef\nhij", EndOfLine]
= {abc,
. def,
. hij}
"""
class WordBoundary(Builtin):
"""
<dl>
<dt>'WordBoundary'
<dd>represents the boundary between words.
</dl>
>> StringReplace["apple banana orange artichoke", "e" ~~ WordBoundary -> "E"]
= applE banana orangE artichokE
"""
class LetterCharacter(Builtin):
"""
<dl>
<dt>'LetterCharacter'
<dd>represents letters.
</dl>
>> StringMatchQ[#, LetterCharacter] & /@ {"a", "1", "A", " ", "."}
= {True, False, True, False, False}
LetterCharacter also matches unicode characters.
>> StringMatchQ["\\[Lambda]", LetterCharacter]
= True
"""
class HexidecimalCharacter(Builtin):
"""
<dl>
<dt>'HexidecimalCharacter'
<dd>represents the characters 0-9, a-f and A-F.
</dl>
>> StringMatchQ[#, HexidecimalCharacter] & /@ {"a", "1", "A", "x", "H", " ", "."}
= {True, True, True, False, False, False, False}
"""
class DigitQ(Builtin):
"""
<dl>
<dt>'DigitQ[$string$]'
yields 'True' if all the characters in the $string$ are digits, and yields 'False' otherwise.
</dl>
>> DigitQ["9"]
= True
>> DigitQ["a"]
= False
>> DigitQ["01001101011000010111010001101000011010010110001101110011"]
= True
>> DigitQ["-123456789"]
= False
#> DigitQ[""]
= True
#> DigitQ["."]
= False
#> DigitQ[1==2]
= False
#> DigitQ[a=1]
= False
"""
rules = {
"DigitQ[string_]": (
"If[StringQ[string], StringMatchQ[string, DigitCharacter...], False, False]"
),
}
class LetterQ(Builtin):
"""
<dl>
<dt>'LetterQ[$string$]'
yields 'True' if all the characters in the $string$ are letters, and yields 'False' otherwise.
</dl>
>> LetterQ["m"]
= True
>> LetterQ["9"]
= False
>> LetterQ["Mathics"]
= True
>> LetterQ["Welcome to Mathics"]
= False
#> LetterQ[""]
= True
#> LetterQ["\\[Alpha]\\[Beta]\\[Gamma]\\[Delta]\\[Epsilon]\\[Zeta]\\[Eta]\\[Theta]"]
= True
"""
rules = {
"LetterQ[string_]": (
"If[StringQ[string], StringMatchQ[string, LetterCharacter...], False, False]"
),
}
class StringMatchQ(Builtin):
r"""
>> StringMatchQ["abc", "abc"]
= True
>> StringMatchQ["abc", "abd"]
= False
>> StringMatchQ["15a94xcZ6", (DigitCharacter | LetterCharacter)..]
= True
#> StringMatchQ["abc1", LetterCharacter]
= False
#> StringMatchQ["abc", "ABC"]
= False
#> StringMatchQ["abc", "ABC", IgnoreCase -> True]
= True
## Words containing nonword characters
#> StringMatchQ[{"monkey", "don't", "AAA", "S&P"}, ___ ~~ Except[WordCharacter] ~~ ___]
= {False, True, False, True}
## Try to match a literal number
#> StringMatchQ[1.5, NumberString]
: String or list of strings expected at position 1 in StringMatchQ[1.5, NumberString].
= StringMatchQ[1.5, NumberString]
Use StringMatchQ as an operator
>> StringMatchQ[LetterCharacter]["a"]
= True
## Abbreviated string patterns Issue #517
#> StringMatchQ["abcd", "abc*"]
= True
#> StringMatchQ["abc", "abc*"]
= True
#> StringMatchQ["abc\\", "abc\\"]
= True
#> StringMatchQ["abc*d", "abc\\*d"]
= True
#> StringMatchQ["abc*d", "abc\\**"]
= True
#> StringMatchQ["abcde", "a*f"]
= False
#> StringMatchQ["abcde", "a@e"]
= True
#> StringMatchQ["aBCDe", "a@e"]
= False
#> StringMatchQ["ae", "a@e"]
= False
"""
attributes = ("Listable",)
options = {
"IgnoreCase": "False",
"SpellingCorrections": "None",
}
messages = {
"strse": "String or list of strings expected at position `1` in `2`.",
}
rules = {
"StringMatchQ[patt_][expr_]": "StringMatchQ[expr, patt]",
}
def apply(self, string, patt, evaluation, options):
"StringMatchQ[string_, patt_, OptionsPattern[%(name)s]]"
py_string = string.get_string_value()
if py_string is None:
return evaluation.message(
"StringMatchQ",
"strse",
Integer(1),
Expression("StringMatchQ", string, patt),
)
re_patt = to_regex(patt, evaluation, abbreviated_patterns=True)
if re_patt is None:
return evaluation.message(
"StringExpression", "invld", patt, Expression("StringExpression", patt)
)
re_patt = anchor_pattern(re_patt)
flags = re.MULTILINE
if options["System`IgnoreCase"] == SymbolTrue:
flags = flags | re.IGNORECASE
if re.match(re_patt, py_string, flags=flags) is None:
return SymbolFalse
else:
return SymbolTrue
class StringJoin(BinaryOperator):
"""
<dl>
<dt>'StringJoin["$s1$", "$s2$", ...]'
<dd>returns the concatenation of the strings $s1$, $s2$, ….
</dl>
>> StringJoin["a", "b", "c"]
= abc
>> "a" <> "b" <> "c" // InputForm
= "abc"
'StringJoin' flattens lists out:
>> StringJoin[{"a", "b"}] // InputForm
= "ab"
>> Print[StringJoin[{"Hello", " ", {"world"}}, "!"]]
| Hello world!
"""
operator = "<>"
precedence = 600
attributes = ("Flat", "OneIdentity")
def apply(self, items, evaluation):
"StringJoin[items___]"
result = ""
items = items.flatten(Symbol("List"))
if items.get_head_name() == "System`List":
items = items.leaves
else:
items = items.get_sequence()
for item in items:
if not isinstance(item, String):
evaluation.message("StringJoin", "string")
return
result += item.value
return String(result)
class StringSplit(Builtin):
"""
<dl>
<dt>'StringSplit["$s$"]'
<dd>splits the string $s$ at whitespace, discarding the
whitespace and returning a list of strings.
<dt>'StringSplit["$s$", "$d$"]'
<dd>splits $s$ at the delimiter $d$.
<dt>'StringSplit[$s$, {"$d1$", "$d2$", ...}]'
<dd>splits $s$ using multiple delimiters.
<dt>'StringSplit[{$s_1$, $s_2, ...}, {"$d1$", "$d2$", ...}]'
<dd>returns a list with the result of applying the function to
each element.
</dl>
>> StringSplit["abc,123", ","]
= {abc, 123}
>> StringSplit["abc 123"]
= {abc, 123}
#> StringSplit[" abc 123 "]
= {abc, 123}
>> StringSplit["abc,123.456", {",", "."}]
= {abc, 123, 456}
>> StringSplit["a b c", RegularExpression[" +"]]
= {a, b, c}
>> StringSplit[{"a b", "c d"}, RegularExpression[" +"]]
= {{a, b}, {c, d}}
#> StringSplit["x", "x"]
= {}
#> StringSplit[x]
: String or list of strings expected at position 1 in StringSplit[x].
= StringSplit[x, Whitespace]
#> StringSplit["x", x]
: Element x is not a valid string or pattern element in x.
= StringSplit[x, x]
#> StringSplit["12312123", "12"..]
= {3, 3}
#> StringSplit["abaBa", "b"]
= {a, aBa}
#> StringSplit["abaBa", "b", IgnoreCase -> True]
= {a, a, a}
"""
rules = {
"StringSplit[s_]": "StringSplit[s, Whitespace]",
}
options = {
"IgnoreCase": "False",
"MetaCharacters": "None",
}
messages = {
"strse": "String or list of strings expected at position `1` in `2`.",
"pysplit": "As of Python 3.5 re.split does not handle empty pattern matches.",
}
def apply(self, string, patt, evaluation, options):
"StringSplit[string_, patt_, OptionsPattern[%(name)s]]"
if string.get_head_name() == "System`List":
leaves = [self.apply(s, patt, evaluation, options) for s in string._leaves]
return Expression("List", *leaves)
py_string = string.get_string_value()
if py_string is None:
return evaluation.message(
"StringSplit", "strse", Integer(1), Expression("StringSplit", string)
)
if patt.has_form("List", None):
patts = patt.get_leaves()
else:
patts = [patt]
re_patts = []
for p in patts:
py_p = to_regex(p, evaluation)
if py_p is None:
return evaluation.message("StringExpression", "invld", p, patt)
re_patts.append(py_p)
flags = re.MULTILINE
if options["System`IgnoreCase"] == SymbolTrue:
flags = flags | re.IGNORECASE
result = [py_string]
for re_patt in re_patts:
result = [t for s in result for t in mathics_split(re_patt, s, flags=flags)]
return string_list("List", [String(x) for x in result if x != ""], evaluation)
class StringPosition(Builtin):
"""
<dl>
<dt>'StringPosition["$string$", $patt$]'
<dd>gives a list of starting and ending positions where $patt$ matches "$string$".
<dt>'StringPosition["$string$", $patt$, $n$]'
<dd>returns the first $n$ matches only.
<dt>'StringPosition["$string$", {$patt1$, $patt2$, ...}, $n$]'
<dd>matches multiple patterns.
<dt>'StringPosition[{$s1$, $s2$, ...}, $patt$]'
<dd>returns a list of matches for multiple strings.
</dl>
>> StringPosition["123ABCxyABCzzzABCABC", "ABC"]
= {{4, 6}, {9, 11}, {15, 17}, {18, 20}}
>> StringPosition["123ABCxyABCzzzABCABC", "ABC", 2]
= {{4, 6}, {9, 11}}
'StringPosition' can be useful for searching through text.
>> data = Import["ExampleData/EinsteinSzilLetter.txt"];
>> StringPosition[data, "uranium"]
= {{299, 305}, {870, 876}, {1538, 1544}, {1671, 1677}, {2300, 2306}, {2784, 2790}, {3093, 3099}}
#> StringPosition["123ABCxyABCzzzABCABC", "ABC", -1]
: Non-negative integer or Infinity expected at position 3 in StringPosition[123ABCxyABCzzzABCABC, ABC, -1].
= StringPosition[123ABCxyABCzzzABCABC, ABC, -1]
## Overlaps
#> StringPosition["1231221312112332", RegularExpression["[12]+"]]
= {{1, 2}, {2, 2}, {4, 7}, {5, 7}, {6, 7}, {7, 7}, {9, 13}, {10, 13}, {11, 13}, {12, 13}, {13, 13}, {16, 16}}
#> StringPosition["1231221312112332", RegularExpression["[12]+"], Overlaps -> False]
= {{1, 2}, {4, 7}, {9, 13}, {16, 16}}
#> StringPosition["1231221312112332", RegularExpression["[12]+"], Overlaps -> x]