dart regex matching and get some information from it

前端 未结 1 1418
旧巷少年郎
旧巷少年郎 2020-12-10 17:13

For practice, I decided to build something like a Backbone router. The user only needs to give the regex string like r\'^first/second/third/$\' and

相关标签:
1条回答
  • 2020-12-10 17:55

    You need to put the parts you want to extract into groups so you can extract them from the match. This is achieved by putting a part of the pattern inside parentheses.

    // added parentheses around \w+ and \d+ to get separate groups 
    String regexString = r'/api/(\w+)/(\d+)/'; // not r'/api/\w+/\d+/' !!!
    RegExp regExp = new RegExp(regexString);
    var matches = regExp.allMatches("/api/topic/3/");
    
    print("${matches.length}");       // => 1 - 1 instance of pattern found in string
    var match = matches.elementAt(0); // => extract the first (and only) match
    print("${match.group(0)}");       // => /api/topic/3/ - the whole match
    print("${match.group(1)}");       // => topic  - first matched group
    print("${match.group(2)}");       // => 3      - second matched group
    

    however, the given regex would also match "/api/topic/3/ /api/topic/4/" as it is not anchored, and it would have 2 matches (matches.length would be 2) - one for each path, so you might want to use this instead:

    String regexString = r'^/api/(\w+)/(\d+)/$';
    

    This ensures that the regex is anchored exactly from beginning to the end of the string, and not just anywhere inside the string.

    0 讨论(0)
提交回复
热议问题