Flutter Dart: RegEx to extract URLs from a String
This may not be the complete regex, but this worked for me for randomly picked links:
void main() { final text = """My website url: https://blasanka.github.io/Google search using: www.google.com, social media is facebook.com, http://example.com/method?param=flutterstackoverflow.com is my greatest website. DartPad share: https://github.com/dart-lang/dart-pad/wiki/Sharing-Guide see this example and edit it here https://dartpad.dev/3d547fa15849f9794b7dbb8627499b00"""; RegExp exp = new RegExp(r'(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+'); Iterable<RegExpMatch> matches = exp.allMatches(text); matches.forEach((match) { print(text.substring(match.start, match.end)); });}
Result:
https://blasanka.github.io/www.google.comfacebook.comhttp://example.com/method?param=flutterstackoverflow.comhttps://github.com/dart-lang/dart-pad/wiki/Sharing-Guidehttps://dartpad.dev/3d547fa15849f9794b7dbb8627499b00
Play with it here: https://dartpad.dev/3d547fa15849f9794b7dbb8627499b00
Try this,
final urlRegExp = new RegExp( r"((https?:www\.)|(https?:\/\/)|(www\.))[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9]{1,6}(\/[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)?");final urlMatches = urlRegExp.allMatches(text);List<String> urls = urlMatches.map( (urlMatch) => text.substring(urlMatch.start, urlMatch.end)) .toList();urls.forEach((x) => print(x));
Getting just the https? and ftp url's that are in quotes is this :
r"([\"'])\s*((?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-zA-Z0-9\u00a1-\uffff]+-?)*[a-zA-Z0-9\u00a1-\uffff]+)(?:\.(?:[a-zA-Z0-9\u00a1-\uffff]+-?)*[a-zA-Z0-9\u00a1-\uffff]+)*(?:\.(?:[a-zA-Z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/(?:(?!\1|\s)[\S\s])*)?)\s*\1"
Where the Url is captured in group 2.