首页 \ 问答 \ 参数化正则表达式用于模式匹配(Parametrized Regex for pattern matching)

参数化正则表达式用于模式匹配(Parametrized Regex for pattern matching)

是否可以匹配从函数返回的正则表达式模式? 我可以这样做吗?

def pattern(prefix: String) = (prefix + "_(\\w+)").r

val x = something match {
  case pattern("a")(key) => "AAAA" + key
  case pattern("b")(key) => "BBBB" + key
}

我无法编译上面的代码。 以下控制台快照显示我收到的错误。 我究竟做错了什么?

scala> def pattern(prefix: String) = (prefix + "_(\\w+)").r
pattern: (prefix: String)scala.util.matching.Regex

scala> def f(s:String) = s match {
     | case pattern("a")(x) => s+x+"AAAAA"
<console>:2: error: '=>' expected but '(' found.
       case pattern("a")(x) => s+x+"AAAAA"
                        ^

Is it possible to match regular expression pattern which is returned from a function? Can I do something like this?

def pattern(prefix: String) = (prefix + "_(\\w+)").r

val x = something match {
  case pattern("a")(key) => "AAAA" + key
  case pattern("b")(key) => "BBBB" + key
}

I cannot compile the above code. The following console snapshot shows an error I get. What am I doing wrong?

scala> def pattern(prefix: String) = (prefix + "_(\\w+)").r
pattern: (prefix: String)scala.util.matching.Regex

scala> def f(s:String) = s match {
     | case pattern("a")(x) => s+x+"AAAAA"
<console>:2: error: '=>' expected but '(' found.
       case pattern("a")(x) => s+x+"AAAAA"
                        ^

原文:https://stackoverflow.com/questions/7418945
更新时间:2024-01-27 20:01

最满意答案

对于具有默认值或默认闭包的存储属性,在调用init方法之前,内存会分配。 您不能使用self或属性来默认值定义其他属性。

您的示例中的闭包通常用于此步骤以定义lazy属性; 它们应该是var并用lazy关键字标记:

class myClass {
    let x: NSString? = nil
    let q: NSString? = {return "q"}() //allocates before class init; deallocates imidiatly
    lazy var y: NSString = {
        let z  = self.x
        return z ?? ""
    }()                               //allocates on first property call; deallocates imidiatly
}

延迟属性的内存将在第一次属性调用时分配。 构造{/*...*/}()意味着此闭包将在调用时执行,并将返回计算结果(您可以在未命名函数中查看此内容),而不是引用此闭包。 这是非常重要的时刻:你没有保留闭包,这个闭包只分配执行时刻并在返回后释放,所以你不需要关心强循环引用问题。

其他的事情 - 当您保存对闭包的引用时:

class myClass {
    let x: NSString? = nil
    var closure: () -> NSString = {return "q"} //allocates before class init; deallocates on references release
    lazy var lazyClosure: () -> NSString = {
        let z  = self.x
        return z ?? ""
    }                                        //allocates on first property call; deallocates on references release
}

此闭包的内存与前一种情况同时分配,但它们将继续存在,直到有任何引用。 你可以在这里查看闭包,就像在不同的对象一样。 这里可能出现循环参考问题。 closure不捕获任何东西,所以它没有问题,但lazyClosure捕获self 。 如果我们永远不会调用lazyClosure就没有问题,因为这个闭包永远不会分配。 但是如果我们将它调用,它将被分配,它将捕获self ,并且将有强循环引用: self指向lazyClosure实例, lazyClosure指向self实例。 要解决这个问题,你应该使其中一个引用弱,你应该使用捕获列表:在lazyClosure体中插入[weak self] in[unowned self] in lazyClosure [unowned self] in[unowned self] in我们的案例中,因为如果财产被称为,那么self就不是nil

lazy var lazyClosure: () -> NSString = {
    [unowned self] in
    let z  = self.x
    return z ?? ""
}

For stored properties with default values or default closures memory allocates immideatly, before init method called. You can not use self or properties for defining other property by default value.

Closures from your example usually used on this step to define lazy properties; they should be var and marked with lazy keyword:

class myClass {
    let x: NSString? = nil
    let q: NSString? = {return "q"}() //allocates before class init; deallocates imidiatly
    lazy var y: NSString = {
        let z  = self.x
        return z ?? ""
    }()                               //allocates on first property call; deallocates imidiatly
}

Memory for lazy properties will be allocated on first property call. Construction {/*...*/}() means that this closure will be executed just at call moment and will return result of calculation (you can look at this like at unnamed function), not reference to this closure. This is very important moment: you are not retain closure, this closure allocates only for execution moment and deallocates just after return, so you don't need care about strong cycle reference problem.

Other thing - when you saving reference to closure:

class myClass {
    let x: NSString? = nil
    var closure: () -> NSString = {return "q"} //allocates before class init; deallocates on references release
    lazy var lazyClosure: () -> NSString = {
        let z  = self.x
        return z ?? ""
    }                                        //allocates on first property call; deallocates on references release
}

Memory for this closures allocates at same time as in previous case, but they will continue to live until have any references. You can look at closures here like at separate objects. Cycle reference problem can arise here. closure is not capture anything, so there are no problems with it, but lazyClosure capture self. If we will never call lazyClosure there will be no problems, since this closure will never allocates. But if we will call it, it will be allocated, it will capture self, and there will be strong cycle reference: self points to lazyClosure instance, lazyClosure points to self instance. To solve this problem you should make one of references weak, you should use capture list: insert [weak self] in or [unowned self] in in lazyClosure body. [unowned self] in in our case, since if property called, then self is not nil.

lazy var lazyClosure: () -> NSString = {
    [unowned self] in
    let z  = self.x
    return z ?? ""
}

相关问答

更多
  • 这里已经提到:on()调用在Lua注册表中保存对回调闭包的引用。 我想这个闭包将从sock对象的__gc元方法中的Lua注册表中清除, 但是如果闭包引用了sock对象,则不会收集sock对象。 要解决这个问题,你应该避免在sendchunk()函数体中对sock upval的引用进行硬编码。 例如,利用传递给回调函数的第一个参数始终是套接字对象的事实。 function sendfile(sock, name) local fd = file.open(name, "r") local fun ...
  • OpenCL认为“本地内存”是: 内存仅在内核执行期间可用,仅由同一工作组的元素共享。 每个工作组只能看到他们的本地内存。 内存使用在编译时是已知的并且是有限的。 它与CPU /多核系统中的寄存器或L1 / L2高速缓存非常相似。 编译器了解目标CPU的寄存器并进行相应的规划。 当调度程序将工作组安排到硬件资源时,将始终确保每个工作组都有足够的内存。 您可以将内核执行中的本地内存视为指向已分配的内存的指针,类似于寄存器或专用内存 。 What OpenCL considers "Local Memory" ...
  • 关于内存分配过于担心是徒劳的。 内存将分配给所有内容,变量,数组,对象等。没有使用变量或对象,你可以用javascript做很多事情,但同样,内存的分配实际上并不是javascript 脚本的域。 任何和所有的JavaScript都会使用一定程度的内存,无论如何。 实际上,我会说,如果你“学会避免使用”对象和数组,你就会被误导或正在学习错误的教训。 避免循环引用,避免每个范围的过多内存消耗,以及通常避免使用紧密循环和其他不良做法锁定浏览器线程更为重要。 例如,在for循环中,避免重新计算for声明中的限制: ...
  • 对于具有默认值或默认闭包的存储属性,在调用init方法之前,内存会分配。 您不能使用self或属性来默认值定义其他属性。 您的示例中的闭包通常用于此步骤以定义lazy属性; 它们应该是var并用lazy关键字标记: class myClass { let x: NSString? = nil let q: NSString? = {return "q"}() //allocates before class init; deallocates imidiatly lazy var y ...
  • 编译器基本上将所有静态的东西和代码编译成保存在磁盘上的映像,例如在Windows上的exe文件等。 当你运行它时,操作系统会分配一些内存并基本上将这个映像复制到内存中,然后开始运行编译后的代码,该代码也被复制到内存中。 在程序中动态分配的内存将在程序执行时分配。 在编译时没有为你的程序分配ram。 “内存在编译时分配”这个陈述是一个概念上的简化。 它的真正含义是存储在编译文件中的初始内存映像是在编译时生成的。 在程序实际运行之前,这不会被加载到RAM中。 这是非常简单但是一般的要点。 查看您的系统上的二进制 ...
  • 首先, mmap是一个系统调用或接口,用于访问系统的虚拟内存。 现在,在linux中(我希望您正在使用* nix),通过延迟加载或更常见的Copy-On-Write实现了很多性能提升。 对于mmap,也实现了这种延迟加载。 当您在文件上调用mmap时,内核不会立即为要映射的文件分配主内存页。 相反,它等待程序从幻觉页面写入/读取,在哪个阶段发生页面错误 ,然后相应的中断处理程序将实际加载可以保存在该页面框架中的特定文件部分(也是页面)表已更新,以便下次在读/写同一页时,它指向一个有效的帧)。 现在,您可以使 ...
  • 我想是的,是的。 这样做会更有效: (function() { var figh = function() { // some code fum(passOnSomeARG); }; var fo = function(y) { // some calculations with y }; var fum = function(x) { // some code fo(x); }; ...
  • 如果没有,那将是灾难性的。 许多人使用这样的技巧来实现他们对malloc细粒度内存管理。 所以,是的,这正是您引用的标准段落的内容。 请注意,它仔细地选择了这些词。 它说 如果值存储在没有声明类型的对象中...... 没有声明类型的此属性在对象的生命周期内不会更改,因此该规定适用于在其中写入新值的任何时间。 如果由于一些奇怪的原因委员会想要说有效类型只能改变一次,他们就会说类似 如果将值存储到没有有效类型的对象中...... If not, that would be catastrophic. Many ...
  • 只要有一种方法可以引用该函数,函数闭包中的任何变量都会保存在内存中。 这里, txtName位于onclick函数的闭包中,因此只要onclick绑定完好且存在“submit”按钮,它就会保留在内存中。 Any variables in the closure of a function are kept in memory as long as there is a way to reference that function. Here, txtName is in the closure of you ...
  • 警告:这直接回答了这个问题,但在你尝试这个之前,首先阅读汉斯的回答并确保你真正了解正在发生的事情并且仍然希望这样做。 固定的GCHandle将完成这项工作,它可以从C ++ / CLI使用。 显然,确保手柄处于固定类型。 这是一个例子: public ref class MemBlockWrapper { MemBlock* mpMemBlock; System::Runtime::InteropServices::GCHandle hFltArray; public: MemBlo ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。