Question

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.

Was it helpful?

Solution 2

Try this regex:

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

And then grab: matches.group(1)

OTHER TIPS

The RegExp class comes with a convenience method for a single match:

RegExp regExp = new RegExp(r"^http://myapp.example.com/#([^?]+)");
var match = regExp.firstMatch("http://myapp.example.com/#fizz?a=1");
print(match[1]);

Note: I used anubhava's regular expression (yours was not escaping the ? correctly).

Note2: even though it's not necessary here, it is usually a good idea to use raw-strings for regular expressions since you don't need to escape $ and \ in them. Sometimes using triple-quote raw-strings are convenient too: new RegExp(r"""some'weird"regexp\$""").

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

Then:

var match = matches.elementAt(0);
print("${match.group(1)}"); // output : fizz
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top