8

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756

3 Answers3

6

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

Florian Loitsch
  • 7,698
  • 25
  • 30
5

Try this regex:

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

And then grab: matches.group(1)

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks @anubhava (+1) - how do I use the [`RegExp`](https://api.dartlang.org/docs/channels/stable/latest/dart_core/RegExp.html) API to obtain a `matches` instance? – IAmYourFaja Jan 03 '14 at 21:46
  • 1
    @CalifornianAcorn It's near the top in the documentation you linked to. `RegExp exp = new RegExp(r"(\w+)"); String str = "Parse my string"; Iterable matches = exp.allMatches(str);` – dee-see Jan 03 '14 at 21:49
  • This might help: http://stackoverflow.com/questions/16522918/dart-regex-matching-and-get-some-information-from-it – anubhava Jan 03 '14 at 21:50
0
String regex = "^http://myapp.example.com/#([^?]+)";

Then:

var match = matches.elementAt(0);
print("${match.group(1)}"); // output : fizz
revo
  • 47,783
  • 14
  • 74
  • 117