Sunshine
Sunshine

Reputation: 334

Extract number matching a length from a string

I have a string like so :

I'd like to extract the postal code (5 digits) from this String

final address = '17 Frog Road, 62000 New York';

Bonus would be to detect & extract the complete String after & including the postal code like so :

final extractedString = '62000 New York';

Upvotes: 0

Views: 696

Answers (3)

Dmytro Popov
Dmytro Popov

Reputation: 182

You may find the Regular expressions useful.

In Dart, you can use them with the RegExp class. Here is an introduction to Regexp in Dart.

In the code it can look like that:

const postalCodePattern = r'\b\d{5}\b';

String? extractPostalCode(String str) => RegExp(postalCodePattern).stringMatch(str);

To extract also anything after the match, the pattern can be modified in the following way:

const postalCodePattern = r'\b\d{5}.*';

That will match any symbols after the 6-digit entry.

Upvotes: 2

NoobN3rd
NoobN3rd

Reputation: 1271

You can use Regular expressions. You can test your example here.

Here is the Regex:

(\d{5})\s(.*)

\d{5} means you're looking for a 5-length number.

\s means a space.

.* means catch any character.

In Dart you can use RegExp to work with regex:

RegExp reg = RegExp(r'(\d{5})\s(.*)');
print(reg.stringMatch('17 Frog Road, 62000 New York'));

Upvotes: 2

Wiktor
Wiktor

Reputation: 775

 final address = '17 Frog Road, 62000 New York';
 final extractedString = address.split(',')[1]; // 62000 New York

Upvotes: 2

Related Questions