diff --git a/lib/src/string.dart b/lib/src/string.dart index b8fe1cb..74dbe57 100644 --- a/lib/src/string.dart +++ b/lib/src/string.dart @@ -113,6 +113,11 @@ extension StringIsLatin1Extension on String { } } +extension StringOnlyDigitsExtension on String { + /// Returns a string containing only ASCII digit characters from this string. + String get onlyDigits => replaceAll(RegExp(r'[^0-9]'), ''); +} + extension StringReversedExtension on String { /// Returns a new string with characters in reversed order. String get reversed { @@ -160,6 +165,11 @@ extension StringIsDoubleExtension on String { bool get isDouble => toDoubleOrNull() != null; } +extension StringIsNumericExtension on String { + /// Returns `true` if the string can be parsed as a number. + bool get isNumeric => toDoubleOrNull() != null; +} + extension StringToDoubleExtension on String { /// Parses the string as a [double] number and returns the result. double toDouble() => double.parse(this); diff --git a/test/string_test.dart b/test/string_test.dart index a6888ef..a1c3121 100644 --- a/test/string_test.dart +++ b/test/string_test.dart @@ -31,6 +31,14 @@ void main() { expect('ő'.isLatin1, false); }); + test('.onlyDigits', () { + expect(''.onlyDigits, ''); + expect('abc'.onlyDigits, ''); + expect('123'.onlyDigits, '123'); + expect('Phone: +1 (555) 123-4567'.onlyDigits, '15551234567'); + expect('a1 b2-c3'.onlyDigits, '123'); + }); + test('.isBlank', () { expect(' '.isBlank, true); expect(' . '.isBlank, false); @@ -132,6 +140,16 @@ void main() { expect('123456789.987654321'.isDouble, true); }); + test('.isNumeric', () { + expect(''.isNumeric, false); + expect('a'.isNumeric, false); + expect('12abc'.isNumeric, false); + expect('1'.isNumeric, true); + expect('-42'.isNumeric, true); + expect('1.0'.isNumeric, true); + expect('123456789.987654321'.isNumeric, true); + }); + test('.toDouble()', () { expect('0'.toDouble(), 0.0); expect('0.0'.toDouble(), 0.0);