Dart: RegExp by example

IAmYourFaja picture IAmYourFaja · Jan 3, 2014 · Viewed 8.6k times · Source

I'm trying to get my Dart web app to: (1) determine if a particular string matches a given regex, and (2) if it does, extract a group/segment out of the string.

Specifically, I want to make sure that a given string is of the following form:

http://myapp.example.com/#<string-of-1-or-more-chars>[?param1=1&param2=2]

Where <string-of-1-or-more-chars> is just that: any string of 1+ chars, and where the query string ([?param1=1&param2=2]) is optional.

So:

  1. Decide if the string matches the regex; and if so
  2. Extract the <string-of-1-or-more-chars> group/segment out of the string

Here's my best attempt:

String testURL = "http://myapp.example.com/#fizz?a=1";
String regex = "^http://myapp.example.com/#.+(\?)+\$";
RegExp regexp= new RegExp(regex);
Iterable<Match> matches = regexp.allMatches(regex);
String viewName = null;
if(matches.length == 0) {
    // testURL didn't match regex; throw error.
} else {
    // It matched, now extract "fizz" from testURL...
    viewName = ??? // (ex: matches.group(2)), etc.
}

In the above code, I know I'm using the RegExp API incorrectly (I'm not even using testURL anywhere), and on top of that, I have no clue how to use the RegExp API to extract (in this case) the "fizz" segment/group out of the URL.

Answer

anubhava picture anubhava · Jan 3, 2014

Try this regex:

String regex = "^http://myapp.example.com/#([^?]+)";

And then grab: matches.group(1)