-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathStringUtils.dart
More file actions
598 lines (552 loc) · 15.5 KB
/
Copy pathStringUtils.dart
File metadata and controls
598 lines (552 loc) · 15.5 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
import 'dart:convert';
import 'dart:io';
import 'dart:math';
///
/// Helper class for String operations
///
class StringUtils {
static AsciiCodec asciiCodec = AsciiCodec();
static final RegExp _ipv4Maybe =
RegExp(r'^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$');
static final RegExp _ipv6 =
RegExp(r'^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$');
///
/// Returns the given string or the default string if the given string is null
///
static String defaultString(String? str, {String defaultStr = ''}) {
return str ?? defaultStr;
}
///
/// Checks if the given String [s] is null or empty
///
static bool isNullOrEmpty(String? s) =>
(s == null || s.isEmpty) ? true : false;
///
/// Checks if the given String [s] is not null or empty
///
static bool isNotNullOrEmpty(String? s) => !isNullOrEmpty(s);
///
/// Transfers the given String [s] from camcelCase to upperCaseUnderscore
/// Example : helloWorld => HELLO_WORLD
///
static String camelCaseToUpperUnderscore(String s) {
var sb = StringBuffer();
var first = true;
s.runes.forEach((int rune) {
var char = String.fromCharCode(rune);
if (isUpperCase(char) && !first) {
sb.write('_');
sb.write(char.toUpperCase());
} else {
first = false;
sb.write(char.toUpperCase());
}
});
return sb.toString();
}
///
/// Transfers the given String [s] from camcelCase to lowerCaseUnderscore
/// Example : helloWorld => hello_world
///
static String camelCaseToLowerUnderscore(String s) {
var sb = StringBuffer();
var first = true;
s.runes.forEach((int rune) {
var char = String.fromCharCode(rune);
if (isUpperCase(char) && !first) {
if (char != '_') {
sb.write('_');
}
sb.write(char.toLowerCase());
} else {
first = false;
sb.write(char.toLowerCase());
}
});
return sb.toString();
}
///
/// Checks if the given string [s] is lower case
///
static bool isLowerCase(String s) {
return s == s.toLowerCase();
}
///
/// Checks if the given string [s] is upper case
///
static bool isUpperCase(String s) {
return s == s.toUpperCase();
}
///
/// Checks if the given string [s] contains only ascii chars
///
static bool isAscii(String s) {
try {
asciiCodec.decode(s.codeUnits);
} catch (e) {
return false;
}
return true;
}
///
/// Capitalize the given string [s]. If [allWords] is set to true, it will capitalize all words within the given string [s].
///
/// The string [s] is there fore splitted by " " (space).
///
/// Example :
///
/// * [s] = "world" => World
/// * [s] = "WORLD" => World
/// * [s] = "the quick lazy fox" => The quick lazy fox
/// * [s] = "the quick lazy fox" and [allWords] = true => The Quick Lazy Fox
///
static String capitalize(String s, {bool allWords = false}) {
if (s.isEmpty) {
return '';
}
s = s.trim();
if (allWords) {
var words = s.split(' ');
var capitalized = [];
for (var w in words) {
capitalized.add(capitalize(w));
}
return capitalized.join(' ');
} else {
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
}
///
/// Reverse the given string [s]
/// Example : hello => olleh
///
static String reverse(String s) {
return String.fromCharCodes(s.runes.toList().reversed);
}
///
/// Counts how offen the given [char] apears in the given string [s].
/// The value [caseSensitive] controlls whether it should only look for the given [char]
/// or also the equivalent lower/upper case version.
/// Example: Hello and char l => 2
///
static int countChars(String s, String char, {bool caseSensitive = true}) {
var count = 0;
s.codeUnits.toList().forEach((i) {
if (caseSensitive) {
if (i == char.runes.first) {
count++;
}
} else {
if (i == char.toLowerCase().runes.first ||
i == char.toUpperCase().runes.first) {
count++;
}
}
});
return count;
}
///
/// Checks if the given string [s] is a digit.
///
/// Will return false if the given string [s] is empty.
///
static bool isDigit(String s) {
if (s.isEmpty) {
return false;
}
if (s.length > 1) {
for (var r in s.runes) {
if (r ^ 0x30 > 9) {
return false;
}
}
return true;
} else {
return s.runes.first ^ 0x30 <= 9;
}
}
///
/// Compares the given strings [a] and [b].
///
static bool equalsIgnoreCase(String a, String b) =>
a.toLowerCase() == b.toLowerCase();
///
/// Checks if the given [list] contains the string [s]
///
static bool inList(String s, List<String> list, {bool ignoreCase = false}) {
for (var l in list) {
if (ignoreCase) {
if (equalsIgnoreCase(s, l)) {
return true;
}
} else {
if (s == l) {
return true;
}
}
}
return false;
}
///
/// Checks if the given string [s] is a palindrome
/// Example :
/// aha => true
/// hello => false
///
static bool isPalindrome(String s) {
for (var i = 0; i < s.length / 2; i++) {
if (s[i] != s[s.length - 1 - i]) return false;
}
return true;
}
///
/// Replaces chars of the given String [s] with [replace].
///
/// The default value of [replace] is *.
/// [begin] determines the start of the 'replacing'. If [begin] is null, it starts from index 0.
/// [end] defines the end of the 'replacing'. If [end] is null, it ends at [s] length divided by 2.
/// If [s] is empty or consists of only 1 char, the method returns null.
///
/// Example :
/// 1234567890 => *****67890
/// 1234567890 with begin 2 and end 6 => 12****7890
/// 1234567890 with begin 1 => 1****67890
///
static String? hidePartial(String s,
{int begin = 0, int? end, String replace = '*'}) {
var buffer = StringBuffer();
if (s.length <= 1) {
return null;
}
if (end == null) {
end = (s.length / 2).round();
} else {
if (end > s.length) {
end = s.length;
}
}
for (var i = 0; i < s.length; i++) {
if (i >= end) {
buffer.write(String.fromCharCode(s.runes.elementAt(i)));
continue;
}
if (i >= begin) {
buffer.write(replace);
continue;
}
buffer.write(String.fromCharCode(s.runes.elementAt(i)));
}
return buffer.toString();
}
///
/// Add a [char] at a [position] with the given String [s].
///
/// The boolean [repeat] defines whether to add the [char] at every [position].
/// If [position] is greater than the length of [s], it will return [s].
/// If [repeat] is true and [position] is 0, it will return [s].
///
/// Example :
/// 1234567890 , '-', 3 => 123-4567890
/// 1234567890 , '-', 3, true => 123-456-789-0
///
static String addCharAtPosition(String s, String char, int position,
{bool repeat = false}) {
if (!repeat) {
if (s.length < position) {
return s;
}
var before = s.substring(0, position);
var after = s.substring(position, s.length);
return before + char + after;
} else {
if (position == 0) {
return s;
}
var buffer = StringBuffer();
for (var i = 0; i < s.length; i++) {
if (i != 0 && i % position == 0) {
buffer.write(char);
}
buffer.write(String.fromCharCode(s.runes.elementAt(i)));
}
return buffer.toString();
}
}
///
/// Splits the given String [s] in chunks with the given [chunkSize].
///
static List<String> chunk(String s, int chunkSize) {
var chunked = <String>[];
for (var i = 0; i < s.length; i += chunkSize) {
var end = (i + chunkSize < s.length) ? i + chunkSize : s.length;
chunked.add(s.substring(i, end));
}
return chunked;
}
///
/// Picks only required string[value] starting [from] and ending at [to]
///
/// Example :
/// pickOnly('123456789',from:3,to:7);
/// returns '34567'
///
static String pickOnly(value, {int from = 1, int to = -1}) {
try {
return value.substring(
from == 0 ? 0 : from - 1, to == -1 ? value.length : to);
} catch (e) {
return value;
}
}
///
/// Removes character with [index] from a String [value]
///
/// Example:
/// removeCharAtPosition('flutterr', 8);
/// returns 'flutter'
static String removeCharAtPosition(String value, int index) {
try {
return value.substring(0, -1 + index) +
value.substring(index, value.length);
} catch (e) {
return value;
}
}
///
///Remove String[value] with [pattern]
///
///[repeat]:boolean => if(true) removes all occurence
///
///[casensitive]:boolean => if(true) a != A
///
///Example: removeExp('Hello This World', 'This'); returns 'Hello World'
///
static String removeExp(String value, String pattern,
{bool repeat = true,
bool caseSensitive = true,
bool multiLine = false,
bool dotAll = false,
bool unicode = false}) {
var result = value;
if (repeat) {
result = value
.replaceAll(
RegExp(pattern,
caseSensitive: caseSensitive,
multiLine: multiLine,
dotAll: dotAll,
unicode: unicode),
'')
.replaceAll(RegExp(' +'), ' ')
.trim();
} else {
result = value
.replaceFirst(
RegExp(pattern,
caseSensitive: caseSensitive,
multiLine: multiLine,
dotAll: dotAll,
unicode: unicode),
'')
.replaceAll(RegExp(' +'), ' ')
.trim();
}
return result;
}
///
/// Takes in a String[value] and truncates it with [length]
/// [symbol] default is '...'
///truncate('This is a Dart Utility Library', 26)
/// returns 'This is a Dart Utility Lib...'
static String truncate(String value, int length, {String symbol = '...'}) {
var result = value;
try {
result = value.substring(0, length) + symbol;
} catch (e) {
print(e.toString());
}
return result;
}
///
/// Generates a Random string
///
/// * [length] = length of string
/// * [alphabet] = add alphabet to string
/// * [uppercase] = adds lowercase alphabet to string
/// * [lowercase] = adds lowercase alphabet to string
/// * [numeric] = add integers to string
/// * [special] = add special characters
/// * [from] = a string that contains the allowed signs to be used for generating the random string
///
static String generateRandomString(
int length, {
alphabet = true,
numeric = true,
special = true,
uppercase = true,
lowercase = true,
String from = '',
}) {
var res = '';
do {
res +=
_randomizer(alphabet, numeric, lowercase, uppercase, special, from);
} while (res.length < length);
var possible = res.split('');
possible.shuffle();
var result = [];
for (var i = 0; i < length; i++) {
var randomNumber = Random().nextInt(length);
result.add(possible[randomNumber]);
}
return result.join();
}
static String _randomizer(bool alphabet, bool numeric, bool lowercase,
bool uppercase, bool special, String from) {
var a = 'ABCDEFGHIJKLMNOPQRXYZ';
var la = 'abcdefghijklmnopqrxyz';
var b = '0123456789';
var c = '~^!@#\$%^&*;`(=?]:[.)_+-|\{}';
var result = '';
if (alphabet) {
if (lowercase) {
result += la;
}
if (uppercase) {
result += a;
}
if (!uppercase && !lowercase) {
result += a;
result += la;
}
}
if (numeric) {
result += b;
}
if (special) {
result += c;
}
if (from != '') {
//if set return it
result = from;
}
return result;
}
///
/// Converts the given String [s] to PascalCase
/// Example: your name => YourName
///
static String toPascalCase(String s) {
final separatedWords = s.split(RegExp(r'[!@#<>?":`~;[\]\\|=+)(*&^%-\s_]+'));
var newString = '';
for (final word in separatedWords) {
newString += word[0].toUpperCase() + word.substring(1).toLowerCase();
}
return newString;
}
///
/// Generates [amount] random strings
///
/// * [length] = length of string
/// * [alphabet] = add alphabet to string
/// * [uppercase] = adds lowercase alphabet to string
/// * [lowercase] = adds lowercase alphabet to string
/// * [numeric] = add integers to string
/// * [special] = add special characters
/// * [from] = a string that contains the allowed signs to be used for generating the random string
///
static List<String> generateRandomStrings(
int amount,
int length, {
alphabet = true,
numeric = true,
special = true,
uppercase = true,
lowercase = true,
String from = '',
}) {
var l = <String>[];
for (var i = 0; i < amount; i++) {
var s = generateRandomString(
length,
alphabet: alphabet,
numeric: numeric,
special: special,
uppercase: uppercase,
lowercase: lowercase,
from: from,
);
l.add(s);
}
return l;
}
///
/// Checks whether the given String [s] is an IPv4 or IPv6 address.
///
static bool isIP(String s, {InternetAddressType? ipType}) {
if (ipType == null || ipType == InternetAddressType.any) {
return isIP(s, ipType: InternetAddressType.IPv4) ||
isIP(s, ipType: InternetAddressType.IPv6);
} else if (ipType == InternetAddressType.IPv4) {
if (!_ipv4Maybe.hasMatch(s)) {
return false;
}
var parts = s.split('.');
parts.sort((a, b) => int.parse(a) - int.parse(b));
return int.parse(parts[3]) <= 255;
} else if (ipType == InternetAddressType.IPv6) {
return _ipv6.hasMatch(s);
}
return false;
}
}
extension Strip on String {
/// Implementation of strip, stripLeft and stripRight
String _strip(
String stripChars, {
bool left = true,
bool right = true,
}) {
if (!left && !right) {
throw ArgumentError('either left or right shall be true in _strip: <$this>');
}
int start = 0;
int end = length;
List<int> sourceChars = runes.toList();
List<int> searchChars = stripChars.runes.toList();
if (left) {
for (int i = 0; i < sourceChars.length; i++) {
if (searchChars.contains(sourceChars[i])) {
start++;
} else {
break;
}
}
}
if (right) {
for (int i = sourceChars.length - 1; i >= 0; i--) {
if (searchChars.contains(sourceChars[i])) {
end--;
} else {
break;
}
}
}
if (start >= end) {
return '';
}
return substring(start, end);
}
/// Return a string after removing any leading and trailing characters specified in [chars]
///
/// '@£^£Some @£^ Thing@@£@^'.strip('@£^') => 'Some @£^ Thing'
String strip(String chars) => _strip(chars, left: true, right: true);
/// Return a string after removing any leading characters specified in [chars]
///
/// '@£^£Some @£^ Thing@@£@^'.stripLeft('@£^') => 'Some @£^ Thing@@£@^'
String stripLeft(String chars) => _strip(chars, left: true, right: false);
/// Return a string after removing any trailing characters specified in [chars]
///
/// '@£^£Some @£^ Thing@@£@^'.strip('@£^') => '@£^£Some @£^ Thing'
String stripRight(String chars) => _strip(chars, left: false, right: true);
}