Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: RegExp by example

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.

like image 203
IAmYourFaja Avatar asked Jan 03 '14 21:01

IAmYourFaja


2 Answers

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\$""").

like image 148
Florian Loitsch Avatar answered Oct 20 '22 11:10

Florian Loitsch


Try this regex:

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

And then grab: matches.group(1)

like image 37
anubhava Avatar answered Oct 20 '22 12:10

anubhava