[英]How can I get this regex right in c#?
我試圖匹配任何具有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"
的圖層type : "Data"
基於這篇關於使用 .net 正則表達式進行括號匹配的帖子,您可以調整呈現的正則表達式:
\\((?>\\((?<c>)|[^()]+|\\)(?<-c>))*(?(c)(?!))\\)
它正在尋找匹配(
和)
集合,您可以簡單地將它們交換為{
和}
(它們在該正則表達式中沒有被轉義)。
然后你可以為layer\\s*
位添加前綴。
對於排除type
<> "Data"
塊的功能,我在 pastebin 中的示例中為所有其他type
關鍵字添加了否定前瞻。 不幸的是,為type: "Data"
添加一個積極的前瞻根本不起作用,我認為如果這樣做了,那將是您最強大的解決方案。
希望您有一個有限的type
值列表,並且您可以將其擴展為一個實用的解決方案:
layer\\s*{(?>{(?<c>)|[^{}](?!type: "Accuracy"|type: "Convolution"|type: "Dropout"|type: "InnerProduct"|type: "LRN"|type: "Pooling"|type: "ReLU"|type: "SoftmaxWithLoss")+|}(?<-c>))*(?(c)(?!))}
在原始正則表達式中使用的關鍵位是[^()]+
,它匹配正則表達式的其他組件正在匹配的括號之間的內容。 我已經將其改編為[^{}]+
- 是“大括號以外的所有內容” - 然后添加了長的“apart from”子句與關鍵字不匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.