我怎样才能在 C# 中得到这个正则表达式?

2024-02-12

我正在尝试匹配任何具有type:"Data",然后将其替换为我想要的文本。
下面给出了一个示例输入,可以有一个或多个:

layer {
  name: "cifar"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TRAIN
  }
  transform_param {
    mean_file: "examples/cifar10/mean.binaryproto"
    mirror: true
    #crop_size: 20 
  }

# this is a comment!
  data_param {
    source: "examples/cifar10/cifar10_train_lmdb"
    batch_size: 100
    backend: LMDB
  }
}
layer {
  name: "cifar"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  transform_param {
    mean_file: "examples/cifar10/mean.binaryproto"
  }
  data_param {
    source: "examples/cifar10/cifar10_test_lmdb"
    batch_size: 25
    backend: LMDB
  }
}

我想出了这个正则表达式:

((layer)( *)((\n))*{((.*?)(\n)*)*(type)( *):( *)("Data")((.*?)(\n)*)*)(.*?)(\n)}

我尝试对此进行建模:

find and select a block starting with layer, 
there can be any number of space characters but after it 
there should be a { character, 
then there can be anything( for making it easier), and then 
there should be a type followed by any number of spaces, then followed by "Data"
then anything can be there, until it is faced with a } character 

但显然这不能正常工作。如果我更改任何这些图层块中的类型,则不会检测到任何内容!,甚至具有以下属性的图层也不会检测到:type : "Data"


基于这个帖子 https://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets/35271017#35271017关于使用 .net 正则表达式进行括号匹配,您可以调整所提供的正则表达式:

\((?>\((?<c>)|[^()]+|\)(?<-c>))*(?(c)(?!))\)

它正在寻找匹配的集合( and )你可以简单地将它们交换为{ and }(在该正则表达式中没有任何内容被转义)。

然后你可以添加前缀layer\s* bit.

对于排除块的功能,其中type"Data"我为所有其他添加了否定的前瞻typePastebin 中示例中的关键字。不幸的是添加了积极的前瞻type: "Data"根本不起作用,我认为如果它起作用,那将是您最强大的解决方案。

希望你有一个有限的清单type值,您可以将其扩展为实用的解决方案:

layer\s*{(?>{(?<c>)|[^{}](?!type: "Accuracy"|type: "Convolution"|type: "Dropout"|type: "InnerProduct"|type: "LRN"|type: "Pooling"|type: "ReLU"|type: "SoftmaxWithLoss")+|}(?<-c>))*(?(c)(?!))}

原始正则表达式中要使用的关键位是[^()]+它匹配正则表达式的其他组件所匹配的括号之间的内容。我已经将其调整为[^{}]+- 是“除大括号之外的所有内容” - 然后添加长“除了”子句与不匹配​​的关键字。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我怎样才能在 C# 中得到这个正则表达式? 的相关文章

随机推荐