NSRegularExpression with template in Swift

I'm obtaining a response to an HTTP POST request with the code

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {data, response, error in if error != nil { println("error=\(error)") return } // Get the response to the HTTP POST var responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!} task.resume()

I tried to define two regular expressions

let regex0: NSRegularExpression = NSRegularExpression(pattern: "<b>District Representatives:</b>", options: NSRegularExpressionOptions.DotMatchesLineSeparators, error: nil)! let regex1: NSRegularExpression = NSRegularExpression(pattern: "\\A.*<b>District Representatives:</b>.*href=\"http://www\.sec\.state\.ma\.us/ele/eledist/con11idx\.htm#D[1-9]\" target=\"_blank\">(.*?)</a>.*href=\"http://www\.sec\.state\.ma\.us/ele/eledist/sen11idx\.htm#[0-9]{0,5}[a-z]{1,20}\" target=\"_blank\">(.*?)</a>.*\"http://www\.sec\.state\.ma\.us/ele/eledist/reps11idx\.htm#[a-z]{1,13}[0-9]{0,2}\" target=\"_blank\">(.*?)</a>.*\\z", options: NSRegularExpressionOptions.DotMatchesLineSeparators, error: nil)!

But Xcode gives me the error message "Expected expression" on the definition of regex1.

I want to test whether responseString is matched by regex0. I tried using

var numberOfMatches: Int = regex0.numberOfMatchesInString(responseString, options:nil, range: (NSMakeRange(0, responseString.length)))

but I got the error message "Use of unresolved identifier responseString"

I'd like to know how to test for the success of a regular expression match. In this case, I could just test whether responseString contains my test string. That seems to work nicely with Swift Strings, but I can't get it to work with an NSString.

I think the pattern in my regex1 regular expression is OK, because I tested the equivalent pattern in TextWrangler. The pattern I used there was

(?s)\A.*<b>District Representatives:</b>.*href="http://www\.sec\.state\.ma\.us/ele/eledist/con11idx\.htm#D[1-9]" target="_blank">(.*?)</a>.*href="http://www\.sec\.state\.ma\.us/ele/eledist/sen11idx\.htm#[0-9]{0,5}[a-z]{1,20}" target="_blank">(.*?)</a>.*"http://www\.sec\.state\.ma\.us/ele/eledist/reps11idx\.htm#[a-z]{1,13}[0-9]{0,2}" target="_blank">(.*?)</a>.*\z

The only (intentional) differences are that in the Swift literal, all the Double-Quotes and Backslashes had to be escaped with a backslash and the TextWrangler pattern starts with (?s) which is the equivalent of NSRegularExpressionOptions.DotMatchesLineSeparators.

I wanted to use regex1 to modify responseString as follows

responseString.replaceMatchesInString(options: nil, range: NSMakeRange(0, responseString.length), withTemplate template: "$1\t$2\t$3")

But that didn't work either.

I naively thought that since I've been using regular expressions for 30 years, that part would be easy. Apparently not.

--------------Solutions-------------

Your regex1 is missing double escapes on the literal dots (see www\.sec\.state\.ma\.us).

The correct regex1 declaration will be

@"\\A.*<b>District Representatives:</b>.*href=\"http://www\\.sec\\.state\\.ma\\.us/ele/eledist/con11idx\\.htm#D[1-9]\" target=\"_blank\">(.*?)</a>.*href=\"http://www\\.sec\\.state\\.ma\\.us/ele/eledist/sen11idx\\.htm#[0-9]{0,5}[a-z]{1,20}\" target=\"_blank\">(.*?)</a>.*\"http://www\\.sec\\.state\\.ma\\.us/ele/eledist/reps11idx\\.htm#[a-z]{1,13}[0-9]{0,2}\" target=\"_blank\">(.*?)</a>.*\\z"

You get Use of unresolved identifier responseString probably because you declared responseString outside the method where you declare and use numberOfMatches.

Category:regex Time:2018-09-15 Views:0
Tags: regex cocoa swift

Related post

  • Can the "using" declaration be used with templates? 2008-12-06

    Is it possible to use the "using" declaration with template base classes? I have read it isn't here but is that because of a technical reason or is it against the C++ standard, and does it apply to gcc or other compilers? If it is not possible, why n

  • Help to correct source code, with template 2009-01-06

    I tried to compile the example posted (http://stackoverflow.com/questions/412165/c-service-providers) and failed to VS8 VC9. I have little experience with template. Any suggestions? Tanks. These are the errors : dictionarystl.cpp(40) : error C2663: '

  • Is that a good idea to define exception with template? 2009-01-20

    I am thinking is that a good idea to define exception with template. Defining different types of exception is a super verbose task. You have to inherit exception, there is nothing changed, just inherit. Like this.. class FooException : public BaseExc

  • Using static variable along with templates 2009-03-03

    I have a template class defined in a header file like this. Here I have defined a static variable as well: #ifndef TEST1_H_ #define TEST1_H_ void f1(); static int count; template <class T> class MyClass { public: void f() { ++count; } }; #endif

  • Can I define custom "surround with" templates in Visual Studio 2008? 2009-07-23

    Can I define custom "surround with" templates in Visual Studio 2008? --------------Solutions------------- Here you go, this is an example to set everything selected inside {} In tools, codesnipet manager. <?xml version="1.0" encoding="utf-8" ?>

  • debugging C++ code with templates and STL with gdb 2009-10-23

    What do gdb users here think about its capabilities in regards to debugging code with templates and STL? Do you use any tricks to make the debugging any simpler? Perhaps some Python scripts? Or are you satisfied the way it is at present in gdb (ver 6

  • Struct with template variables in C++ 2010-03-15

    I'm playing around with templates. I'm not trying to reinvent the std::vector, I'm trying to get a grasp of templateting in C++. Can I do the following? template <typename T> typedef struct{ size_t x; T *ary; }array; What I'm trying to do is a

  • C++: combine const with template arguments 2010-05-12

    The following example is working when I manualy replace T wirh char *, but why is not working as it is: template <typename T> class A{ public: A(const T _t) { } }; int main(){ const char * c = "asdf"; A<char *> a(c); } When compiling with

  • When does a const return type interfere with template instantiation? 2010-05-28

    From Herb Sutter's GotW #6 Return-by-value should normally be const for non-builtin return types. ... Note: Lakos (pg. 618) argues against returning const value, and notes that it is redundant for builtins anyway (for example, returning "const int"),

  • g++ duplicate symbol error when working with templates (noob question) 2010-07-23

    So I'm trying to pick C++, and to do so I decided to write a generic Group class using templates, that takes a Type and size as template parameters: in group.h: #ifndef __GROUP_H #define __GROUP_H #define MAX_SIZE 10 /********************************

  • Call destructor via void pointer with templates 2010-10-24

    I wrote a class to contain my objects in it. The code is: class objectPool { private: struct itemType_{uint count; void* object;}; std::multimap< std::string, itemType_ > pool_; public: template<class T> bool addItem(std::string key, T*

  • C++ Polymorphism with template class 2010-11-04

    template<typename Type> class List { public: List(void); ~List(void); ... } which inherited by template<typename Type> class LinkedList : public List<Type> { public: LinkedList(void); ~LinkedList(void); ... } but when I List<int

  • C++0x lambdas with template parameters? 2010-11-08

    Possible Duplicate: Can lambda functions be templated? Is it possible to have a c++0x lambda with template parameters? For example: template <typename T> [=](const T *x) {} What I am trying to do is to code a static for loop on a type list (var

  • Building HTML with templates versus building it in javascript? 2010-11-21

    I recently started making web apps, and while I make some stuff that works, I'm not sure of the best practices. Up to now, I've mostly used the templating systems of Django, web.py and PHP. But now that I'm using jQuery and nice ajaxy magic to get da

  • Getting list of object names in module with template haskell? 2010-12-05

    I'd like to be able to take a file with declarations such as: test_1 = assert $ 1 == 1 test_2 = assert $ 2 == 1 and generate a basic run function like main = runTests [test_1, test2] The goal is to get something like Python's nosetest. Can I do this

  • Testing Classes that Use Collaborators with Templated Methods 2010-12-07

    I like the things that templates methods can do for me, since they can be used to dramatically simplify some code I'd otherwise have to write over and over. However, I have a very hard time testing any classes that depend on collaborators that have p

  • Specialized partialization with template parameters 2011-02-07

    I have a template class ,MyClass<class E,class T>,and i want to use : std::unary_function<T,bool> _predicate; std::binary_function<T,E,void> _swaper; as template template parameters in my class , notice the bool and the void which i

  • How to make closed source for the library written with template in C++ 2011-03-06

    After reading this article Storing C++ template function definitions in a .CPP file, I know that the definition of a class that uses template has to be written in the header file in some way. So a client user can use it by importing the header files.

  • Default values in templates with template arguments ( C++ ) 2011-03-14

    Assume I have a template (called ExampleTemplate) that takes two arguments: a container type (e.g. list, vector) and a contained type (e.g. float, bool, etc). Since containers are in fact templates, this template has a template param. This is what I

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.403 (s). 13 q(s)