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';
CodePudding user response:
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.
CodePudding user response:
final address = '17 Frog Road, 62000 New York';
final extractedString = address.split(',')[1]; // 62000 New York
CodePudding user response:
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'));