STRling 2.1.0__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,29 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: STRling
3
- Version: 2.1.0
3
+ Version: 2.2.0
4
4
  Description-Content-Type: text/markdown
5
5
 
6
6
  # STRling
7
7
 
8
- ## The Next Generation of Regular Expressions
8
+ ## 🗺️ Project Overview
9
9
 
10
10
  STRling is a next-generation production-grade syntax designed as a user interface for writing powerful regular expressions (RegEx) with an object-oriented approach and instructional error handling. STRling recognizes the cryptic nature of raw regular expression can be challenging and susceptibility to errors, which is why STRling looks and feels nothing like RegEx while maintaining the same power and flexibility. String validation should be simple and enjoyable, not a hassle. Best of all, STRling syntax is built upon the RegEx engine, making it fully compatible with all libraries that accept RegEx along with the traditional RegEx methods built-in to Python.
11
11
 
12
- ### Why STRling?
12
+ ### 🗝️ Key Features
13
13
 
14
- 1. Beginner Friendly: You need ZERO knowledge of RegEx jargon to create powerful and clear to read patterns.
15
- 2. Common Templates Built-in: STRling has predefined templates for commonly used patterns, so forget about even writing our simple syntax for most cases. (phone number, email, url... etc.)
16
- 3. Reliable Logic: STRling exclusively utilizes built-in python libraries, making it a reliable package.
17
- 4. Instructional Error Handling: Errors inevitably occur by drafting invalid patterns, so STRling explains to the developer exactly what was done wrong and how to correct it.
18
- 5. Consistent and Readable: Make your projects clear and consistent by using STRling rather than the individual library string validators that each have their own syntax (Sqlite3, Sequelize, Postgres, WTForms... etc.).
14
+ 1. **Beginner Friendly:** You need ZERO knowledge of RegEx jargon to create powerful and clear to read patterns.
15
+ 2. **Common Templates Built-in:** STRling has predefined templates for commonly used patterns, so forget about even writing our simple syntax for most cases. (phone number, email, url... etc.)
16
+ 3. **Reliable Logic:** STRling exclusively utilizes built-in python libraries, making it a reliable package.
17
+ 4. **Instructional Error Handling:** Errors inevitably occur by drafting invalid patterns, so STRling explains to the developer exactly what was done wrong and how to correct it.
18
+ 5. **Consistent and Readable:** Make your projects clear and consistent by using STRling rather than the individual library string validators that each have their own syntax (Sqlite3, Sequelize, Postgres, WTForms... etc.).
19
19
 
20
20
  These key features collectively emphasis and fortify the claim that STRling truly is a next-generation production-grade syntax for pattern handling.
21
21
 
22
- ### STRling's Mission
22
+ ### 🎯 Project Mission
23
23
 
24
24
  Our mission is to make RegEx a distant and outdated syntax by abstracting the complexities of RegEx into a clean, readable, and powerful interface. We strive to simplify string operations and ensure that developers can focus on building their applications without the steep learning curve of traditional RegEx. The previous alternative to RegEx was to learn the string validation syntax specific to each user input library, but STRling aims to unify the disparate syntaxes found across various libraries and frameworks into one simple library using only built-in Python packages.
25
25
 
26
- ### Installation
26
+ ### 💾 Installation
27
27
 
28
28
  Install STRling via pip:
29
29
 
@@ -31,7 +31,7 @@ Install STRling via pip:
31
31
  pip install STRling
32
32
  ```
33
33
 
34
- # STRling in action!
34
+ ## ✨ STRling in action!
35
35
 
36
36
  ```python
37
37
  from STRling import simply as s
@@ -45,7 +45,7 @@ import re
45
45
  # - 1234567890
46
46
 
47
47
  # Separator: either space or hyphen
48
- separator = s.in_(' -')
48
+ separator = s.in_chars(' -')
49
49
 
50
50
  # Optional area code part: 123 even if in parenthesis like (123)
51
51
  area_code = s.merge( # notice we use merge since we don't want to name the group with parenthesis
@@ -95,7 +95,7 @@ for match in matches:
95
95
  # Last Part: 7890
96
96
  ```
97
97
 
98
- # STRling Package Documentation
98
+ ## 📑 STRling Documentation
99
99
 
100
100
  ### Don't worry if you can't remember it all!
101
101
  We have well structured and explanatory docustrings for each function
@@ -173,7 +173,7 @@ s.between('a', 'z') # Matches any lowercase letter from 'a' to 'z'.
173
173
  s.between('A', 'Z') # Matches any uppercase letter from 'A' to 'Z'.
174
174
 
175
175
  # Matches any provided patterns, but they can't include subpatterns.
176
- s.in_(s.letter(), s.digit(), ',.') # Matches any letter, digit, comma, and period.
176
+ s.in_chars(s.letter(), s.digit(), ',.') # Matches any letter, digit, comma, and period.
177
177
  # A composite pattern is one consisting of subpatterns (created by constructors and lookarounds).
178
178
 
179
179
  ####################
@@ -272,10 +272,16 @@ s.merge(s.behind(s.digit()), s.letter()) # Only matches a letter preceded by a
272
272
 
273
273
  Simplify your string validation and matching tasks with STRling, the all-in-one solution for developers who need a powerful yet user-friendly tool for working with strings. No longer write RegEx using complex jargon or the various syntaxes string validation specific to independent libraries. Download and start using STRling today!
274
274
 
275
- ---
275
+ ## 🌎 Locations
276
+ [![STRling on PyPI](https://img.shields.io/pypi/v/STRling?color=blue&logo=pypi)](https://pypi.org/project/STRling/)
277
+ [![STRling on GitHub](https://img.shields.io/badge/GitHub-black?logo=github&logoColor=white)](https://github.com/TheCyberLocal/STRling)
276
278
 
277
- To learn more about STRling, checkout [STRling on PyPI](https://pypi.org/project/STRling/) and [STRling on GitHub](https://github.com/TheCyberLocal/STRling).
279
+ ## 🌐 Socials
280
+ [![LinkedIn](https://img.shields.io/badge/LinkedIn-%230077B5.svg?logo=linkedin&logoColor=white)](https://linkedin.com/in/tzm01)
278
281
 
279
- To learn more about me, checkout [My LinkedIn](https://www.linkedin.com/in/tzm01/).
282
+ ## 💖 Support
283
+ If you find my content helpful or interesting, consider buying me a coffee. Every cup is greatly appreciated and fuels my work!
280
284
 
281
- To learn more about traditional RegEx syntax, checkout [My RegEx Docs](https://github.com/TheCyberLocal/styled-coding-notes/blob/main/regEx.md).
285
+ [![Buy Me a Coffee](https://img.shields.io/badge/-buy_me_a%C2%A0coffee-gray?logo=buy-me-a-coffee)](https://buymeacoffee.com/thecyberlocal)
286
+ [![PayPal](https://img.shields.io/badge/PayPal-00457C?logo=paypal&logoColor=white)](https://www.paypal.com/paypalme/TheCyberLocal)
287
+ [![Venmo](https://img.shields.io/badge/Venmo-008CFF?logo=venmo&logoColor=white)](https://www.venmo.com/TheCyberLocal)
@@ -1,29 +1,24 @@
1
- Metadata-Version: 2.1
2
- Name: STRling
3
- Version: 2.1.0
4
- Description-Content-Type: text/markdown
5
-
6
1
  # STRling
7
2
 
8
- ## The Next Generation of Regular Expressions
3
+ ## 🗺️ Project Overview
9
4
 
10
5
  STRling is a next-generation production-grade syntax designed as a user interface for writing powerful regular expressions (RegEx) with an object-oriented approach and instructional error handling. STRling recognizes the cryptic nature of raw regular expression can be challenging and susceptibility to errors, which is why STRling looks and feels nothing like RegEx while maintaining the same power and flexibility. String validation should be simple and enjoyable, not a hassle. Best of all, STRling syntax is built upon the RegEx engine, making it fully compatible with all libraries that accept RegEx along with the traditional RegEx methods built-in to Python.
11
6
 
12
- ### Why STRling?
7
+ ### 🗝️ Key Features
13
8
 
14
- 1. Beginner Friendly: You need ZERO knowledge of RegEx jargon to create powerful and clear to read patterns.
15
- 2. Common Templates Built-in: STRling has predefined templates for commonly used patterns, so forget about even writing our simple syntax for most cases. (phone number, email, url... etc.)
16
- 3. Reliable Logic: STRling exclusively utilizes built-in python libraries, making it a reliable package.
17
- 4. Instructional Error Handling: Errors inevitably occur by drafting invalid patterns, so STRling explains to the developer exactly what was done wrong and how to correct it.
18
- 5. Consistent and Readable: Make your projects clear and consistent by using STRling rather than the individual library string validators that each have their own syntax (Sqlite3, Sequelize, Postgres, WTForms... etc.).
9
+ 1. **Beginner Friendly:** You need ZERO knowledge of RegEx jargon to create powerful and clear to read patterns.
10
+ 2. **Common Templates Built-in:** STRling has predefined templates for commonly used patterns, so forget about even writing our simple syntax for most cases. (phone number, email, url... etc.)
11
+ 3. **Reliable Logic:** STRling exclusively utilizes built-in python libraries, making it a reliable package.
12
+ 4. **Instructional Error Handling:** Errors inevitably occur by drafting invalid patterns, so STRling explains to the developer exactly what was done wrong and how to correct it.
13
+ 5. **Consistent and Readable:** Make your projects clear and consistent by using STRling rather than the individual library string validators that each have their own syntax (Sqlite3, Sequelize, Postgres, WTForms... etc.).
19
14
 
20
15
  These key features collectively emphasis and fortify the claim that STRling truly is a next-generation production-grade syntax for pattern handling.
21
16
 
22
- ### STRling's Mission
17
+ ### 🎯 Project Mission
23
18
 
24
19
  Our mission is to make RegEx a distant and outdated syntax by abstracting the complexities of RegEx into a clean, readable, and powerful interface. We strive to simplify string operations and ensure that developers can focus on building their applications without the steep learning curve of traditional RegEx. The previous alternative to RegEx was to learn the string validation syntax specific to each user input library, but STRling aims to unify the disparate syntaxes found across various libraries and frameworks into one simple library using only built-in Python packages.
25
20
 
26
- ### Installation
21
+ ### 💾 Installation
27
22
 
28
23
  Install STRling via pip:
29
24
 
@@ -31,7 +26,7 @@ Install STRling via pip:
31
26
  pip install STRling
32
27
  ```
33
28
 
34
- # STRling in action!
29
+ ## ✨ STRling in action!
35
30
 
36
31
  ```python
37
32
  from STRling import simply as s
@@ -45,7 +40,7 @@ import re
45
40
  # - 1234567890
46
41
 
47
42
  # Separator: either space or hyphen
48
- separator = s.in_(' -')
43
+ separator = s.in_chars(' -')
49
44
 
50
45
  # Optional area code part: 123 even if in parenthesis like (123)
51
46
  area_code = s.merge( # notice we use merge since we don't want to name the group with parenthesis
@@ -95,7 +90,7 @@ for match in matches:
95
90
  # Last Part: 7890
96
91
  ```
97
92
 
98
- # STRling Package Documentation
93
+ ## 📑 STRling Documentation
99
94
 
100
95
  ### Don't worry if you can't remember it all!
101
96
  We have well structured and explanatory docustrings for each function
@@ -173,7 +168,7 @@ s.between('a', 'z') # Matches any lowercase letter from 'a' to 'z'.
173
168
  s.between('A', 'Z') # Matches any uppercase letter from 'A' to 'Z'.
174
169
 
175
170
  # Matches any provided patterns, but they can't include subpatterns.
176
- s.in_(s.letter(), s.digit(), ',.') # Matches any letter, digit, comma, and period.
171
+ s.in_chars(s.letter(), s.digit(), ',.') # Matches any letter, digit, comma, and period.
177
172
  # A composite pattern is one consisting of subpatterns (created by constructors and lookarounds).
178
173
 
179
174
  ####################
@@ -272,10 +267,16 @@ s.merge(s.behind(s.digit()), s.letter()) # Only matches a letter preceded by a
272
267
 
273
268
  Simplify your string validation and matching tasks with STRling, the all-in-one solution for developers who need a powerful yet user-friendly tool for working with strings. No longer write RegEx using complex jargon or the various syntaxes string validation specific to independent libraries. Download and start using STRling today!
274
269
 
275
- ---
270
+ ## 🌎 Locations
271
+ [![STRling on PyPI](https://img.shields.io/pypi/v/STRling?color=blue&logo=pypi)](https://pypi.org/project/STRling/)
272
+ [![STRling on GitHub](https://img.shields.io/badge/GitHub-black?logo=github&logoColor=white)](https://github.com/TheCyberLocal/STRling)
276
273
 
277
- To learn more about STRling, checkout [STRling on PyPI](https://pypi.org/project/STRling/) and [STRling on GitHub](https://github.com/TheCyberLocal/STRling).
274
+ ## 🌐 Socials
275
+ [![LinkedIn](https://img.shields.io/badge/LinkedIn-%230077B5.svg?logo=linkedin&logoColor=white)](https://linkedin.com/in/tzm01)
278
276
 
279
- To learn more about me, checkout [My LinkedIn](https://www.linkedin.com/in/tzm01/).
277
+ ## 💖 Support
278
+ If you find my content helpful or interesting, consider buying me a coffee. Every cup is greatly appreciated and fuels my work!
280
279
 
281
- To learn more about traditional RegEx syntax, checkout [My RegEx Docs](https://github.com/TheCyberLocal/styled-coding-notes/blob/main/regEx.md).
280
+ [![Buy Me a Coffee](https://img.shields.io/badge/-buy_me_a%C2%A0coffee-gray?logo=buy-me-a-coffee)](https://buymeacoffee.com/thecyberlocal)
281
+ [![PayPal](https://img.shields.io/badge/PayPal-00457C?logo=paypal&logoColor=white)](https://www.paypal.com/paypalme/TheCyberLocal)
282
+ [![Venmo](https://img.shields.io/badge/Venmo-008CFF?logo=venmo&logoColor=white)](https://www.venmo.com/TheCyberLocal)
@@ -0,0 +1,2 @@
1
+ from . import simply
2
+ from .patterns import patterns
@@ -0,0 +1,68 @@
1
+ from STRling import simply as s
2
+
3
+ class Patterns:
4
+ @property
5
+ def phone_number_US(self):
6
+ """
7
+ Returns a pattern for matching US phone numbers.
8
+
9
+ Primary match examples:
10
+ - (123) 456-7890
11
+ - 123-456-7890
12
+ - 123 456 7890
13
+ - 123.456.7890
14
+
15
+ Edge-cases to consider:
16
+ - (123-456.7890
17
+ - 123).456 7890
18
+ - (123 456-7890
19
+
20
+ Named groups:
21
+ - 'first': The first set of 3 digits.
22
+ - 'second': The second set of 3 digits.
23
+ - 'third': The last set of 4 digits.
24
+
25
+ Returns:
26
+ - Pattern: A Pattern object for matching US phone numbers.
27
+ """
28
+ first = s.group('first', s.digit(3))
29
+ second = s.group('second', s.digit(3))
30
+ third = s.group('third', s.digit(4))
31
+ first_sect = s.merge(s.may('('), first, s.may(')'))
32
+ sep = s.in_chars('-. ')
33
+ phone_number = s.merge(first_sect, sep, second, sep, third)
34
+ phone_number_pattern = s.merge(s.not_behind(s.digit()), phone_number, s.not_ahead(s.digit()))
35
+ return phone_number_pattern
36
+
37
+ @property
38
+ def ipv4(self):
39
+ """
40
+ Returns a pattern for matching IPv4 addresses.
41
+
42
+ Primary match examples:
43
+ - 192.168.1.1
44
+ - 10.0.0.1
45
+ - 172.16.254.1
46
+ - 255.255.255.255
47
+ - 0.0.0.0
48
+
49
+ Edge-cases to consider:
50
+ - 999.999.999.999
51
+ - 256.256.256.256
52
+ - 192.168.1.256
53
+
54
+ Captured groups:
55
+ - Numbered 1 to 4 for each octet.
56
+
57
+ Returns:
58
+ - Pattern: A Pattern object for matching IPv4 addresses.
59
+ """
60
+ ipv4_pattern = s.capture(
61
+ s.digit(1, 3), '.',
62
+ s.digit(1, 3), '.',
63
+ s.digit(1, 3), '.',
64
+ s.digit(1, 3)
65
+ )
66
+ return ipv4_pattern
67
+
68
+ patterns = Patterns()
@@ -0,0 +1,421 @@
1
+
2
+ from .pattern import STRlingError, Pattern, lit
3
+
4
+
5
+
6
+ ############################
7
+ # Constructor Methods
8
+ ########
9
+
10
+
11
+ def any_of(*patterns):
12
+ """
13
+ Matches any provided pattern, including patterns consisting of subpatterns.
14
+
15
+ Example: simply as s
16
+ - Matches 3 digits followed by 3 letters.
17
+
18
+ pattern1 = s.merge(s.digit(3), s.letter(3))
19
+
20
+ - Matches 3 letters followed by 3 digits.
21
+
22
+ pattern2 = s.merge(s.letter(3), s.digit(3))
23
+
24
+ - Matches either pattern1 or pattern2.
25
+
26
+ either_pattern = s.any_of(pattern1, pattern2)
27
+
28
+ Parameters:
29
+ - *patterns (Pattern/str): One or more patterns to be matched.
30
+
31
+ Returns:
32
+ - Pattern: A Pattern object representing the OR combination of the given patterns.
33
+ """
34
+
35
+ # Check all patterns are instance of Pattern or str
36
+ clean_patterns = []
37
+ for pattern in patterns:
38
+ if isinstance(pattern, str):
39
+ pattern = lit(pattern)
40
+
41
+ if not isinstance(pattern, Pattern):
42
+ message = """
43
+ Method: simply.any_of(*patterns)
44
+
45
+ The parameters must be instances of `Pattern` or `str`.
46
+
47
+ Use a string such as "123abc$" to match literal characters, or use a predefined set like `simply.letter()`.
48
+ """
49
+ raise STRlingError(message)
50
+
51
+ clean_patterns.append(pattern)
52
+
53
+
54
+ # Count named groups and raise error if not unique
55
+ named_group_counts = {}
56
+
57
+ for pattern in clean_patterns:
58
+ for group_name in pattern.named_groups:
59
+ if group_name in named_group_counts:
60
+ named_group_counts[group_name] += 1
61
+ else:
62
+ named_group_counts[group_name] = 1
63
+
64
+ duplicates = {name: count for name, count in named_group_counts.items() if count > 1}
65
+ if duplicates:
66
+ duplicate_info = ", ".join([f"{name}: {count}" for name, count in duplicates.items()])
67
+ message = f"""
68
+ Method: simply.any_of(*patterns)
69
+
70
+ Named groups must be unique.
71
+ Duplicate named groups found: {duplicate_info}.
72
+
73
+ If you need later reference change the named group argument to `simply.capture()`.
74
+ If you don't need later reference change the named group argument to `simply.merge()`.
75
+ """
76
+ raise STRlingError(message)
77
+
78
+ sub_names = named_group_counts.keys()
79
+
80
+ joined = '|'.join(f'(?:{str(p)})' for p in clean_patterns)
81
+ new_pattern = f'(?:{joined})'
82
+
83
+ return Pattern(new_pattern, composite=True, named_groups=sub_names)
84
+
85
+ def may(*patterns):
86
+ """
87
+ Optionally matches the provided patterns. If this pattern is absent, surrounding patterns can still match.
88
+
89
+ Example: simply as s
90
+ - Matches any letter, along with any trailing digit.
91
+
92
+ pattern = s.merge(s.letter(), s.may(s.digit()))
93
+
94
+ In the text, "AB2" the pattern above matches 'A' and 'B2'.
95
+
96
+ Parameters:
97
+ - *patterns (Pattern/str): One or more patterns to be optionally matched.
98
+
99
+ Returns:
100
+ - Pattern: A Pattern object representing the optional match of the given patterns.
101
+ """
102
+
103
+ # Check all patterns are instance of Pattern or str
104
+ clean_patterns = []
105
+ for pattern in patterns:
106
+ if isinstance(pattern, str):
107
+ pattern = lit(pattern)
108
+
109
+ if not isinstance(pattern, Pattern):
110
+ message = """
111
+ Method: simply.may(*patterns)
112
+
113
+ The parameters must be instances of `Pattern` or `str`.
114
+
115
+ Use a string such as "123abc$" to match literal characters, or use a predefined set like `simply.letter()`.
116
+ """
117
+ raise STRlingError(message)
118
+
119
+ clean_patterns.append(pattern)
120
+
121
+
122
+ # Count named groups and raise error if not unique
123
+ named_group_counts = {}
124
+
125
+ for pattern in clean_patterns:
126
+ for group_name in pattern.named_groups:
127
+ if group_name in named_group_counts:
128
+ named_group_counts[group_name] += 1
129
+ else:
130
+ named_group_counts[group_name] = 1
131
+
132
+ duplicates = {name: count for name, count in named_group_counts.items() if count > 1}
133
+ if duplicates:
134
+ duplicate_info = ", ".join([f"{name}: {count}" for name, count in duplicates.items()])
135
+ message = f"""
136
+ Method: simply.may(*patterns)
137
+
138
+ Named groups must be unique.
139
+ Duplicate named groups found: {duplicate_info}.
140
+
141
+ If you need later reference change the named group argument to `simply.capture()`.
142
+ If you don't need later reference change the named group argument to `simply.merge()`.
143
+ """
144
+ raise STRlingError(message)
145
+
146
+ sub_names = named_group_counts.keys()
147
+
148
+ joined = merge(*clean_patterns)
149
+ new_pattern = f'{joined}?'
150
+
151
+ return Pattern(new_pattern, composite=True, named_groups=sub_names)
152
+
153
+
154
+
155
+ def merge(*patterns):
156
+ """
157
+ Combines the provided patterns into one larger pattern.
158
+
159
+ Example: simply as s
160
+ - Matches any digit, comma, or period.
161
+
162
+ merged_pattern = s.merge(s.digit(), ',.')
163
+
164
+ Parameters:
165
+ - *patterns (Pattern/str): One or more patterns to be concatenated.
166
+
167
+ Returns:
168
+ - Pattern: A Pattern object representing the concatenation of the given patterns.
169
+ """
170
+
171
+ # Check all patterns are instance of Pattern or str
172
+ clean_patterns = []
173
+ for pattern in patterns:
174
+ if isinstance(pattern, str):
175
+ pattern = lit(pattern)
176
+
177
+ if not isinstance(pattern, Pattern):
178
+ message = """
179
+ Method: simply.merge(*patterns)
180
+
181
+ The parameters must be instances of `Pattern` or `str`.
182
+
183
+ Use a string such as "123abc$" to match literal characters, or use a predefined set like `simply.letter()`.
184
+ """
185
+ raise STRlingError(message)
186
+
187
+ clean_patterns.append(pattern)
188
+
189
+
190
+ # Count named groups and raise error if not unique
191
+ named_group_counts = {}
192
+
193
+ for pattern in clean_patterns:
194
+ for group_name in pattern.named_groups:
195
+ if group_name in named_group_counts:
196
+ named_group_counts[group_name] += 1
197
+ else:
198
+ named_group_counts[group_name] = 1
199
+
200
+ duplicates = {name: count for name, count in named_group_counts.items() if count > 1}
201
+ if duplicates:
202
+ duplicate_info = ", ".join([f"{name}: {count}" for name, count in duplicates.items()])
203
+ message = f"""
204
+ Method: simply.merge(*patterns)
205
+
206
+ Named groups must be unique.
207
+ Duplicate named groups found: {duplicate_info}.
208
+
209
+ If you need later reference change the named group argument to `simply.capture()`.
210
+ If you don't need later reference change the named group argument to `simply.merge()`.
211
+ """
212
+ raise STRlingError(message)
213
+
214
+ sub_names = named_group_counts.keys()
215
+
216
+ joined = ''.join(str(p) for p in clean_patterns)
217
+ new_pattern = f'(?:{joined})'
218
+
219
+ return Pattern(new_pattern, composite=True, named_groups=sub_names)
220
+
221
+ def capture(*patterns):
222
+ """
223
+ Creates a numbered group that can be indexed for extracting this part of the match.
224
+
225
+ - Captures CANNOT be invoked with a range.
226
+
227
+ s.capture(s.digit(), s.letter())(1, 2) <== INVALID
228
+
229
+ - Captures CAN be invoked with a number of copies.
230
+
231
+ s.capture(s.digit(), s.letter())(3) <== VALID
232
+
233
+ Example: simply as s
234
+ - Matches any digit, comma, or period.
235
+
236
+ captured_pattern = s.capture(s.digit(), ',.')
237
+
238
+
239
+ Parameters:
240
+ - *patterns (Pattern/str): One or more patterns to be captured.
241
+
242
+ Returns:
243
+ - Pattern: A Pattern object representing the capturing group of the given patterns.
244
+
245
+ Referencing: simply as s
246
+ three_digit_group = s.capture(s.digit(3))
247
+
248
+ four_groups_of_three = three_digit_groups(4)
249
+
250
+ example_text = "Here is a number: 111222333444"
251
+
252
+ match = re.search(str(four_groups_of_three), example_text) # Notice str(pattern)
253
+
254
+ print("Full Match:", match.group())
255
+ print("First:", match.group(1))
256
+ print("Second:", match.group(2))
257
+ print("Third:", match.group(3))
258
+ print("Fourth:", match.group(4))
259
+
260
+ # Output:
261
+ # Full Match: 111222333444
262
+ # First: 111
263
+ # Second: 222
264
+ # Third: 333
265
+ # Fourth: 444
266
+ """
267
+
268
+ # Check all patterns are instance of Pattern or str
269
+ clean_patterns = []
270
+ for pattern in patterns:
271
+ if isinstance(pattern, str):
272
+ pattern = lit(pattern)
273
+
274
+ if not isinstance(pattern, Pattern):
275
+ message = """
276
+ Method: simply.capture(*patterns)
277
+
278
+ The parameters must be instances of `Pattern` or `str`.
279
+
280
+ Use a string such as "123abc$" to match literal characters, or use a predefined set like `simply.letter()`.
281
+ """
282
+ raise STRlingError(message)
283
+
284
+ clean_patterns.append(pattern)
285
+
286
+
287
+ # Count named groups and raise error if not unique
288
+ named_group_counts = {}
289
+
290
+ for pattern in clean_patterns:
291
+ for group_name in pattern.named_groups:
292
+ if group_name in named_group_counts:
293
+ named_group_counts[group_name] += 1
294
+ else:
295
+ named_group_counts[group_name] = 1
296
+
297
+ duplicates = {name: count for name, count in named_group_counts.items() if count > 1}
298
+ if duplicates:
299
+ duplicate_info = ", ".join([f"{name}: {count}" for name, count in duplicates.items()])
300
+ message = f"""
301
+ Method: simply.capture(*patterns)
302
+
303
+ Named groups must be unique.
304
+ Duplicate named groups found: {duplicate_info}.
305
+
306
+ If you need later reference change the named group argument to `simply.capture()`.
307
+ If you don't need later reference change the named group argument to `simply.merge()`.
308
+ """
309
+ raise STRlingError(message)
310
+
311
+ sub_names = named_group_counts.keys()
312
+
313
+ joined = ''.join(str(p) for p in clean_patterns)
314
+ new_pattern = f'({joined})'
315
+
316
+ return Pattern(new_pattern, composite=True, numbered_group=True, named_groups=sub_names)
317
+
318
+ def group(name, *patterns):
319
+ """
320
+ Creates a unique named group that can be referenced for extracting this part of the match.
321
+
322
+ - Groups CANNOT be invoked with a range.
323
+
324
+ s.group('name', s.digit())(1, 2) <== INVALID
325
+
326
+ Example: simply as s
327
+ - Matches any digit followed by a comma and period.
328
+
329
+ named_pattern = s.group('my_group', s.digit(), ',.')
330
+
331
+ Parameters:
332
+ - name (str): The name of the capturing group.
333
+ - *patterns (Pattern/str): One or more patterns to be captured.
334
+
335
+ Returns:
336
+ - Pattern: A Pattern object representing the named capturing group of the given patterns.
337
+
338
+ Referencing: simply as s
339
+ first = s.group("first", s.digit(3))
340
+
341
+ second = s.group("second", s.digit(3))
342
+
343
+ third = s.group("third", s.digit(4))
344
+
345
+ phone_number_pattern = s.merge(first, "-", second, "-", third)
346
+
347
+ example_text = "Here is a phone number: 123-456-7890."
348
+
349
+ match = re.search(str(phone_number_pattern), example_text) # Notice str(pattern)
350
+
351
+ print("Full Match:", match.group())
352
+ print("First:", match.group("first"))
353
+ print("Second:", match.group("second"))
354
+ print("Third:", match.group("third"))
355
+
356
+ # Output:
357
+ # Full Match: 123-456-7890
358
+ # First: 123
359
+ # Second: 456
360
+ # Third: 7890
361
+ """
362
+
363
+ if not isinstance(name, str):
364
+ message = """
365
+ Method: simply.group(name, *patterns)
366
+
367
+ The group is missing a specified name.
368
+ The `name` parameter must be a string like 'group_name'.
369
+ """
370
+ raise STRlingError(message)
371
+
372
+
373
+ # Check all patterns are instance of Pattern or str
374
+ clean_patterns = []
375
+ for pattern in patterns:
376
+ if isinstance(pattern, str):
377
+ pattern = lit(pattern)
378
+
379
+ if not isinstance(pattern, Pattern):
380
+ message = """
381
+ Method: simply.group(name, *patterns)
382
+
383
+ The parameters must be instances of `Pattern` or `str`.
384
+
385
+ Use a string such as "123abc$" to match literal characters, or use a predefined set like `simply.letter()`.
386
+ """
387
+ raise STRlingError(message)
388
+
389
+ clean_patterns.append(pattern)
390
+
391
+
392
+ # Count named groups and raise error if not unique
393
+ named_group_counts = {}
394
+
395
+ for pattern in clean_patterns:
396
+ for group_name in pattern.named_groups:
397
+ if group_name in named_group_counts:
398
+ named_group_counts[group_name] += 1
399
+ else:
400
+ named_group_counts[group_name] = 1
401
+
402
+ duplicates = {name: count for name, count in named_group_counts.items() if count > 1}
403
+ if duplicates:
404
+ duplicate_info = ", ".join([f"{name}: {count}" for name, count in duplicates.items()])
405
+ message = f"""
406
+ Method: simply.group(name, *patterns)
407
+
408
+ Named groups must be unique.
409
+ Duplicate named groups found: {duplicate_info}.
410
+
411
+ If you need later reference change the named group argument to `simply.capture()`.
412
+ If you don't need later reference change the named group argument to `simply.merge()`.
413
+ """
414
+ raise STRlingError(message)
415
+
416
+ sub_names = named_group_counts.keys()
417
+
418
+ joined = ''.join(str(p) for p in clean_patterns)
419
+ new_pattern = f'(?P<{name}>{joined})'
420
+
421
+ return Pattern(new_pattern, composite=True, named_groups=[name, *sub_names])